JavaScript: for-of Loop
New in JS2015.
for (variable of iterable) {…}
The for-of loop is a syntax that lets you go thru iterable object's values.
Standard builtin iterable objects include: string, array, set, map. [see Iterable]
What is the difference between for-in loop and for-of loop?
The for-in loop
for (let var in object) {…}
can be used on any object, and iterates its enumerable string property keys, and will go up to the prototype chain.
[see for-in Loop]
The for-of loop
for (let var of iterable) {…}
work with iterable object only.
The value that is iterated may or may not be properties.
For example, for array object, it goes thru the array values (which is property values)
, but for {Map, Set} objects, it iterates their special values, for string object, it iterates thru the characters.
Does not go up to the prototype chain.
[see Iterable]
(Technically, the value iterated is anything iterable[Symbol.iterator].next()
returns.)
Example: Iterate Array
// for-of loop on array for (let x of [3, 4, 5]) console.log(x); // prints 3 4 5
[see Array Object]
Here is “for of” loop with index and value:
// for-of loop on array let aa = ["a", "b", "c"]; for (let [i,x] of aa.entries()) { console.log(i,x); } // prints // 0 'a' // 1 'b' // 2 'c'
[see Array.prototype.entries]
Example: Iterate String
When used on string, it goes thru each char, not 16 bits unit. This fixed a long time JavaScript problem. [see Character, Code Unit, Codepoint]
// for of loop thru string. // in each iteration, the value is a unicode char, not as 16 bits byte sequence for (let x of "ab😂d") { console.log(x); } // prints // a // b // 😂 // d
Iterate Set
// for-of loop over set object let mySet = new Set([3,4,5]); for (let v of mySet) { console.log(v); } // prints // 3 // 4 // 5