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
pearA 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 20Notes
Unlike forEach(), for...of supports break, continue and await. Plain objects cannot be looped this way — use Object.entries(obj).
See also
- for...in — Loops over the property names of an object.
- Array.prototype.forEach — Runs a function for every element of an array.
- Array.prototype.entries — Returns index–element pairs for a for...of loop.
- Symbol.iterator — A special key that makes an object iterable in for...of and spread.
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.