function*naturals(){let n =1;while(true)yield n++;}// Get first 5 even squaresconst result =naturals().map(n => n **2).filter(n => n %2===0).take(5).toArray();console.log(result);// [4, 16, 36, 64, 100]
Note ES2025. Chainable lazy operations on any iterator. Unlike array methods, these process elements one at a time, making them memory-efficient for large or infinite sequences.
Frequently asked questions
How does JavaScript handle lazy iteration?
JavaScript covers this with 2 copy-ready snippets on this page. The "Generator Functions" snippet in JavaScript uses `function* name() { yield value; }`.
Which code does the JavaScript example use?
The "Generator Functions" snippet uses `function* name() { yield value; }`, from the Functions section of the JavaScript cheat sheet.
What other JavaScript snippets are shown for "lazy iteration"?
Besides "Generator Functions", this page also shows "Iterator Helpers (ES2025)".
Is there anything to watch out for?
Yes. For "Generator Functions": Generators are lazy -- they produce values on demand. Execution pauses at each yield and resumes when next() is called.