On this page
Iterators, Generators & Iterator Helpers
Prev: ES Modules & Error Handling | Up: tutorials | Next: web
Rel: Proxy & Well-Known Symbols, Event Loop & Async Programming, Python Iterators and Generators
Ref: MDN Web Docs — Iterators and Generators
Tags: #public #web #javascript #tutorials #iterators #generators
Contents
- > The Iteration Protocol (`Symbol.iterator`)
- > Generators (`function*`, `yield`, `yield*`)
- > Lazy `Iterator.prototype` Helpers
The Iteration Protocol (Symbol.iterator)
An object is iterable if it defines [Symbol.iterator]() returning an iterator with a .next() method yielding { value, done }:
const range = (start, end) => ({
[Symbol.iterator]() {
let cur = start;
return {
next() {
return cur < end ? { value: cur++, done: false } : { value: undefined, done: true };
},
};
},
});
console.log([...range(1, 5)]); // [1, 2, 3, 4]
Generators (function*, yield, yield*)
Generator functions pause and resume lazily on yield, and delegate to nested iterables with yield*:
function* fibonacci() {
let [a, b] = [0, 1];
while (true) {
yield a;
[a, b] = [b, a + b];
}
}
function* flatten(items) {
for (const item of items) {
if (Array.isArray(item)) yield* flatten(item);
else yield item;
}
}
console.log([...flatten([1, [2, [3, 4]], 5])]); // [1, 2, 3, 4, 5]
Lazy Iterator.prototype Helpers
Modern JavaScript provides lazy pipeline methods directly on iterators (.map(), .filter(), .take(), .drop(), .toArray()), avoiding intermediate array allocations:
const firstSixEvens = fibonacci()
.filter((n) => n % 2 === 0)
.take(6)
.toArray();
console.log(firstSixEvens); // [0, 2, 8, 34, 144, 610]
Linked from
Related notes
- tuts/javascript/tutorials Linked here; links to this page; shared tags: #javascript, #tutorials, #web
- tuts/javascript/tutorials/modules_and_error_handling Linked here; links to this page; shared tags: #javascript, #tutorials, #web
- tuts/javascript/tutorials/event_loop_and_async_programming Linked here; shared tags: #javascript, #tutorials, #web
- tuts/python3/tutorials/advanced_python_internals/iterators_and_generators Linked here; shared tags: #generators, #iterators, #tutorials
- tuts/javascript/builtins/proxy_and_symbols Linked here; shared tags: #javascript, #web
- tuts/web Linked here; shared tags: #web
- tuts/javascript/tutorials/core_syntax_and_types shared tags: #javascript, #tutorials, #web
- tuts/javascript/tutorials/functions_closures_and_this shared tags: #javascript, #tutorials, #web
- tuts/javascript/tutorials/prototype_chain_and_new_flow shared tags: #javascript, #tutorials, #web
- tuts/css/tutorials shared tags: #tutorials, #web