In this blog, we will learn how we can use foreach in the latest ES6 i.e. ECMAScript 2015. In ES6 the new syntax that we will use to iterate over the elements of array is “for-of”. Hence here we will learn how we can iterate through the elements of an array as per ES6. It avoids the pitfalls that we met in “for-in”. Unlike forEach() , “for-of” will work with break, return and continue. “for-in” loop is used for looping through the object properties and “for-of” is for looping through values of array.
The new syntax for looping through the array elements in ES6 is as below:
for (var val of anArray) {
console.log(val);
}
It works well for objects such as DOM NodeLists which is like an array. It works for strings also, where the strings are sequence of unicode characters.
It works for Map
and Set
objects. Where Map is used to eliminate the duplicates.
// making a Set from an array of toys and removing the duplicate one.
var uniqueToy = new Set(toys);
After setting an array of unique toys we can loop over its elements as below:
for (var toy of uniqueToy) {
console.log(toy);
}
In "Map" we have data in key-value pairs. Now to unpack the key and value into two different variables, we again will use "for-of" as below:
for (var [key, val] of statezipCode) {
console.log(key + "'s zip code is: " + val);
}
Note: for-of not works with plain old Objects, but to iterate through an object's properties we can use for-in or Object.keys().
0 Comment(s)