In this tutorial, I will introduce you to the for … of statement in js that allows you to loop through an iterable object.
ES6 introduced a new structure for … of that creates a loop over iterable objects such as Array , Map , Set or any other iterable object.
Below is an example for … of
1 2 3 4 | for (variable of iterable) { // statements } |
Let’s see some examples of using for … of
Array
The following example shows you how to use for … of to loop through the elements of an array
1 2 3 4 5 6 7 8 9 | let scores = [10, 20, 30]; for (let score of scores) { score = score + 5; console.log(score); } // 15 // 25 // 35 |
If you don’t change the variable inside the loop, you should use const instead of let like so:
1 2 3 4 5 6 7 | for (const score of scores) { console.log(score); } // 10 // 20 // 30 |
String
The following example shows you how to use for … of to loop through the elements of a string
1 2 3 4 5 6 7 8 | let str = 'abc'; for (let c of str) { console.log(c); } // a // b // c |
Map
The following example shows you how to use for … of to loop through the elements of a map
1 2 3 4 5 6 7 8 9 10 11 12 13 | var colors = new Map(); colors.set('red', '#ff0000'); colors.set('green', '#00ff00'); colors.set('blue', '#0000ff'); for (let color of colors) { console.log(color); } // ["red", "#ff0000"] // ["green", "#00ff00"] // ["blue", "#0000ff"] |
Set
The following example shows you how to use for … of to loop through the elements of a set
1 2 3 4 5 6 7 8 9 | let nums = new Set([1, 2, 3]); for (let num of nums) { console.log(num); // } // 1 // 2 // 3 |
for … of vs. for … in
The for … in loop loops through all the enumerable properties of an object. It is not iterated over a set such as Array , Map , Set
Unlike for … in loops, for … of loops iterate over a set, instead of an object. In fact, for … of iterates over the elements of any set with the [Symbol.iterator] attribute.
The following example illustrates the difference between for … of and for … in
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | let numbers = [6, 7, 8]; numbers.foo = "foo"; for (let i in numbers) { console.log(i); } // 0 // 1 // 2 // foo for (let i of numbers) { console.log(i); } // 6 // 7 // 8 |
In this article, I have used for … of in js to loop through a collection
See you in the next article