Back to Lessons

JavaScript Generators

April 5, 2026

Generators (ES6)

Functions producing sequence of values over time.

Generator Example

function* numberGenerator() {
    yield 1;
    yield 2;
    yield 3;
}

let gen = numberGenerator();
console.log(gen.next().value); // 1
console.log(gen.next().value); // 2

// Infinite sequence
function* infinite() {
    let i = 0;
    while (true) yield i++;
}

// For...of iteration
for (let value of numberGenerator()) {
    console.log(value);
}

Key Points

  • function* and yield keywords.
  • generator.next() produces next value.
  • Pauses/resumes execution.
  • Memory efficient for large sequences.