For OF loop is quite similar to For IN loop. Just that it provides a little easier way to iterate an Array.
Let us see in the below example.
Let's say, we have a Arrays that stores the Cities.
And as we know, square brackets [] are used to represent an Arrays.
cities = ["Mumbai", "Paris", "London"]
Now, if we want to Iterate through the above Array using for loop.
<html> <body> <script language = "javascript" type = "text/javascript"> var cities = ["Mumbai", "Paris", "London"] for (x of cities) { document.write(x, ", ") } </script> </body> </html>
So, if we look at the above code, the for OF loop,
for (x of cities) { document.write(x, ", ") }
Gets the values from the cities Array.
And in each Iteration, prints the value of x.
Let us see the Iterations.
Below is the Array (i.e. cities).
cities = ["Mumbai", "Paris", "London"]
Or
And the for loop starts,
for (x of cities)
In the first Iteration, the first element is taken from the Array cities and put into the variable x.
And the first element in the cities Array is Mumbai. So, Mumbai is put into x.
And the value of x is printed.
Similarly, in the second Iteration, the second element is taken from the Array cities and put into the variable x.
And the second element in the cities Array is Paris. So, Paris is put into x replacing Mumbai.
And the value of x is printed.
Similarly, in the third Iteration, the third element is taken from the Array cities and put into the variable x.
And the third element in the cities Array is London. So, Paris is put into x replacing Paris.
And the value of x is printed.