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.