For of Loop Javascript

For of Loop Javascript

Well, the for… of the loop is kind of interesting, and convenient to be used, when we want to iterate through iterable objects majorly, like arrays, strings, map, set (there is another loop called as for… in, which we are going to majorly use with objects(with non-symbol enumerable properties(if you did not get this, simply assume that we are going to iterate through enumerable properties of an object))).

The syntax is also simple, and much more readable so that it also becomes easy for us, to go through the program.

First of all, let’s have a look at how are we doing this with help of the regular for loop(about which, we already know) –


As you can see, we got an array, and then we are running a regular for loop, to iterate through the array. If we try to have a look at the output, it comes out to be something like this –

As you can see, we were able to iterate through the array using the regular for loop. But, now, let’s do this using the for… of the loop. First of all, let’s have a look at the syntax, and then we will jump to the example –

for (variable of iterable){
// some statements…
}

Here, the variable is like a container, which is going to hold a new value from the iterable, in each iteration. We can create the variable using the let, const, or var keyword. This thing is very simple, and even if you haven’t got this thing, don’t worry, because this is just the syntax, and we are going to have a look at the program.

Now, let’s have a look at the example –


As you can see, how simple the syntax is, and also, we are able to iterate through each element from the array here. If we try to have a look at the output now, the output is something like this –

As you can see, we could not see any change from the previous output, where we had done the same thing with the regular for loop. This is simply amazing, and we can make use of the for… of loop as and when required. This syntax looks like much more readable, and easy to be understood and implemented. You can also try some examples, using the for… of loop, so as to get familiar with the concept.