Encodera

Thanks for reading!

Donate to the site — we work hard for you.

JavaScript reference

for...of

Loops over the values of arrays, strings, Maps, Sets and other iterables.

Available since: ES2015

Syntax

for (const item of iterable) { … }

Examples

Looping over an array:

for (const fruit of ['apple', 'pear']) {
  console.log(fruit);
}

Output:

apple
pear

A string, the index via entries() and break:

for (const char of 'hey') {
  console.log(char);
}
 
for (const [i, n] of [10, 20, 30, 40].entries()) {
  if (n > 20) break;
  console.log(i, n);
}

Output:

h
e
y
0 10
1 20

Notes

Unlike forEach(), for...of supports break, continue and await. Plain objects cannot be looped this way — use Object.entries(obj).

See also

In the tutorial

  • Loops — The while, for and for...of loops in JavaScript — the counter, the step, looping over a string and accumulating a result.

Thanks for reading!

Donate to the site — we work hard for you.