JavaScript Runtime Semantics
Iterables, Iterators & Generators
The iterable protocol lets objects define how they are consumed by
for...of, spread, destructuring, and many collection APIs. Generators provide a compact way to produce custom iterators.- An iterable has
Symbol.iterator - An iterator has
next() - Generators create iterators with
yield - Iteration can be lazy
for...ofandfor...inare different
| Term | Shape | Used by |
|---|---|---|
| Iterable | Has Symbol.iterator | for...of, spread, destructuring |
| Iterator | Has next() | Protocol consumer |
| Generator | function* with yield | Lazy iterator authoring |
| Async iterable | Has Symbol.asyncIterator | for await...of |
function* range(start, end) {
for (let i = start; i <= end; i++) {
yield i
}
}
console.log([...range(1, 3)]) // [1, 2, 3]