For in Loop Javascript

The for… in the loop is an amazing thing, which we are going to use majorly for iterating through the enumerable properties of objects. Majorly, we are going to iterate through objects, which are keyed with strings, and not symbols.

Well, if the above short explanation confuses you, don’t worry, because we are now going to consider an example, through which, we can understand the use of for in loop. But first of all, let’s have a look at the syntax for the same –

for (variable in object){
//some statements…
}

Here, the variable is like a container, that is going to hold a different property name(key) on each iteration. Do not worry if the syntax has not given the basic idea about the concept. We are going to have a look at an example, which demonstrates the use them for… in the loop.

For in Loop Javascript

Let’s have a look at the example now –

As you can see, the syntax is pretty simple to be used, and much more readable. So, we are going to get the property names over here. After we have the property names, it is easy to access the values of those properties. If we have a look at the output, the output comes out to be something like this –

As you can see in the output, we got the keys from the object. Once we have the keys, it is super easy for getting the values associated with the keys.

In the above program, we are simply getting the values associated with those keys.

If we try to have a look at the output, it comes out to be something like this –


As you can see, we got the values associated with those keys easily. So, this is how we can make use of the for-in loop.

Now, we have seen both the loops, the for-of loop, and the for-in loop as well. But what is the difference? Well, it is clear, that both the loops are helping iterate over something. The main difference lies in what they are iterating over.

Here, the for-of loop is going to help us iterate through the values of the iterable object(like an array, map, set, etc)

On the other hand, the for-in loop is going to help us iterate over the enumerable properties of an object.