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
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.
/* use for-of loop to go over characters in string. */ for (let x of "ab🦋d") { console.log(x); } /* a b 🦋 d */
Example: loop over set object
/* 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 */