for of loop
The for…of statement creates a loop iterating over iterable objects (including Array, Map, Set, String, TypedArray, arguments object etc).
for..of loop is added in ES6.
Check the compatibility table for usage in various browsers.
Syntax :
for (variable of iterable_object) {
statement
}
Example : Iterating over an array using for of loop
1 2 3 4 5 6 7 8 | var daysOfWeek = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; for(let i of daysOfWeek){ document.write(i); } |
Output:
Sunday Monday Tuesday Wednesday Thursday Friday Saturday
Example : Iterating over characters of a String using for of loop
1 2 3 4 5 6 7 8 | var message = "HelloWorld"; for(let i of message){ document.write(i + " , "); } |
Output:
H , e , l , l , o , W , o , r , l , d ,
Example : Iterating over a Map using for of loop
1 2 3 4 5 6 7 8 9 10 11 | var capital = new Map(); capital.set("India", "Delhi"); capital.set("Japan", "Tokyo"); capital.set("China", "Beijing"); for (var [key, value] of capital) { console.log("Capital of " + key + " is " + value); } |
Output:
Difference between for..in and for..of loops in JavaScript
Using the for..in loop, you can iterate over indexes of the list array.
Using the for..of loop, you iterate over the values stored in the array.
Here is an example to compare the for..of to for..in:
1 2 3 4 5 6 | for(var i in daysOfWeek){ document.write(i); } |
Output:
0123456
1 2 3 4 5 6 | for(var i of daysOfWeek){ document.write(i); } |
Output:
Sunday Monday Tuesday Wednesday Thursday Friday Saturday
© 2016, www.topjavatutorial.com. All rights reserved. On republishing this post, you must provide link to original post