logo

Iterators and Generators

Explain iteration protocols and how generators simplify writing lazy sequences.

Short explanation

Iterators provide a standardized way to traverse collections. Generators (function*) produce iterators and enable lazy computation through yield.

Syntax example

function* idGenerator() {
  let i = 0;
  while (true) yield i++;
}
const g = idGenerator();
console.log(g.next().value); // 0

How JS handles it internally

Generators pause and resume execution, preserving their execution context between yield calls. They are useful for building lazy streams and complex async flows with libraries.

FAQ

Q: Are generators used often today?

A: Less for everyday code, but they are powerful for certain libraries and advanced control flow.