JS: for-of Loop
(new in ECMAScript 2015)
for-of Loop
The for-of loop is a syntax that lets you loop over Iterable Object's items.
for (variable of iterable) {body}
Example: Loop Over Array
for-of loop on Array
for (let x of [3, 4, 5]) { console.log(x); } /* 3 4 5 */
Example: Loop Over Array with Index and Value
Go over array with index and value. By Destructuring Assignment and Array.prototype.entries.
let xx = ["a", "b", "c"]; /* loop over array with index and value */ for (let [i, v] of xx.entries()) { console.log(i, v); } /* prints 0 a 1 b 2 c */
Example: Loop Over Characters in String
When used on string, it goes thru each char, not String Code Unit . This fixed a long time JavaScript problem.
/* iterate characters in string, by for-of loop. */ for (let x of "ab🦋d") { console.log(x);} /* a b 🦋 d */
Example: Loop Over Set Object
〔see JS: the Set Object Tutorial〕
/* for-of loop over set object */ let xx = new Set([3, 4, 5]); for (let v of xx) { console.log(v); } /* prints 3 4 5 */
Loop Over Map Object
JavaScript. Iterable, Iterator
- JS: Iterable Object
- JS: for-of Loop
- JS: Array.from
- JS: Spread Operator (triple dots)
- JS: Iterator
- JS: Iterator.prototype
- JS: Generator
- JS: Generator Function (asterisk)
- JS: Interface
- JS: Iterable Interface
- JS: Iterator Interface
- JS: IteratorResult Interface
- JS: Test If Object is Iterable or Iterator 📜