JS: for-of Loop
New in JS2015.
for-of Loop
The for-of loop is a syntax that lets you go thru Iterable Object 's values.
for (variable of iterable) {body}
Example: Loop Over Array
for-of loop on Array Object
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.
/* for-of loop thru string. In each iteration, the value is a unicode char, not code unit. */ for (let x of "abπd") { console.log(x); } /* prints 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 */