Lazy iteration

2 snippets in JavaScript

JSJavaScript

Generator Functions

JS · Functions
Syntax
function* name() { yield value; }
Example
function* idGenerator(start = 1) {
  let id = start;
  while (true) {
    yield id++;
  }
}
const ids = idGenerator(100);
console.log(ids.next().value); // 100
console.log(ids.next().value); // 101
console.log(ids.next().value); // 102

Note Generators are lazy -- they produce values on demand. Execution pauses at each yield and resumes when next() is called.

Iterator Helpers (ES2025)

JS · Modern Features
Syntax
iterator.map(fn)
iterator.filter(fn)
iterator.take(n)
iterator.drop(n)
iterator.flatMap(fn)
iterator.toArray()
Example
function* naturals() {
  let n = 1;
  while (true) yield n++;
}

// Get first 5 even squares
const 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.