Iterators and the for...of loop
The for...of loop operates on a sequence of values sourced from an iterable object, such as arrays, array-like objects, DOM collections, iterators, generators, and user-defined iterables. All built-in iterators inherit from the Iterator class.
Overview
The for...of loop operates on a sequence of values sourced from an iterable object, such as arrays, array-like objects, DOM collections, iterators, generators, and user-defined iterables. All built-in iterators inherit from the Iterator class.
Browser support
| Feature | Desktop | Mobile | ||||
|---|---|---|---|---|---|---|
| Chrome | Edge | Firefox | Safari | Chrome Android | Safari iOS | |
| 38 | 12 | 17 | 10 | 38 | 10 | |
| The [Symbol.iterator]() method of Iterator instances implements the iterable protocol and allows built-in iterators to be consumed by most syntaxes expecting iterables, such as the spread syntax and Statements/for...of loops. It returns the value of this, which is the iterator object itself. | 38 | 12 | 36 | 10 | 38 | 10 |
| Other | ||||||
| The for...of statement executes a loop that operates on a sequence of values sourced from an iterable object. Iterable objects include instances of built-ins such as Array, String, TypedArray, Map, Set, NodeList (and other DOM collections), as well as the Functions/arguments object, generators produced by generator functions, and user-defined iterables. | 38 | 12 | 13 | 7 | 38 | 7 |
| Statement | ||||||
closing iterators Closing iterators | 51 | 14 | 53 | 7 | 51 | 7 |
- This feature was removed in a later browser version (36)
- This feature was removed in a later browser version (27)
- Previously available under a different name: @@iterator (27)
- A placeholder property named `@@iterator` is used.
- Previously available under a different name: iterator (17)
- A placeholder property named `iterator` is used.
- Before Firefox 51, using the `for...of` loop construct with the `const` keyword threw a `SyntaxError` ("missing = in const declaration").
Syntax
// for...of loop
for (const value of [1, 2, 3]) {
console.log(value);
}
// Custom iterator
const range = {
from: 1, to: 5,
[Symbol.iterator]() {
let current = this.from;
return {
next: () => current <= this.to
? { value: current++, done: false }
: { done: true }
};
}
}; Live demo
Use cases
Using Iterators and the for...of loop
The for...of loop operates on a sequence of values sourced from an iterable object, such as arrays, array-like objects, DOM collections, iterators, generators, and user-defined iterables. All built-in iterators inherit from the Iterator class.
Cautions
- No specific concerns. Stable across all major browsers.
Accessibility
- When updating the DOM dynamically, announce important changes to assistive technology with aria-live regions.
Related links
Powered by web-features