JS: for-of Loop (iterable)

By Xah Lee. Date: . Last updated: .

(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 (const x of [3, 4, 5]) {
  console.log(x);
}
/*
3
4
5
*/

Example: loop over array with index and value

const xx = ["a", "b", "c"];

/* loop over array with index and value */
for (const [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 (const x of "ab🦋d") {
 console.log(x);
}
/*
a
b
🦋
d
*/

Loop over map object