For...of Loop
Starting from ECMAScript 6 (or ES6), we have a new way to iterate over arrays: the for...of loop. It's very similar to the for...in loop, but instead of the in keyword, we use the of keyword.
Iterating an Array with for...of
-
Given our
colorsarray:const colors = ['red', 'green', 'blue']; -
We can write a
for...ofloop to iterate over it.for (let color of colors) { console.log(color); }
-
Explanation:
-
You can see with this new
for...ofloop, we don't have to deal with the index. We don't have to access the element at a given index (e.g.,colors[index]). -
In each iteration, the
colorvariable (our loop variable) will hold one of the items in the array.
-
-
Expected Output:
When this code is run (or "when I save the changes"), you see the items logged directly to the console:
Output:
red
green
blue
Key Takeaway: for...in vs. for...of
To summarize everything:
-
We use the
for...inloop to iterate over the properties of an object. -
We use the
for...ofloop to iterate over the elements or items in an array.