JS Guide
HomeQuestionsSearchResources
Search

Built for developers preparing for JavaScript, React & TypeScript interviews.

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionsjavascript
PrevNext
javascript
senior
generators

What are Generators in JavaScript and when would you use them?

generators
iterators
yield
lazy-evaluation
es6
Quick Answer

Generators are functions that can pause execution and resume later, yielding multiple values over time. They're defined with function* syntax and return an iterator. Use cases include lazy evaluation, infinite sequences, and custom iterables.

Detailed Explanation

Generator Basics:

  • Defined with function* syntax
  • Use yield to pause and emit values
  • Return an iterator with next() method
  • Can receive values via next(value)

Iterator Protocol:

  • next() returns { value, done }
  • Generator completes when function returns or no more yields

Use Cases:

  1. Lazy evaluation: Generate values on demand
  2. Infinite sequences: Memory-efficient infinite data
  3. Custom iterables: Make objects work with for...of
  4. Async flow control: Foundation for async/await
  5. State machines: Manage complex state transitions

Code Examples

Basic generator syntax
function* numberGenerator() {
  console.log('Starting');
  yield 1;
  console.log('After first yield');
  yield 2;
  console.log('After second yield');
  yield 3;
  console.log('Ending');
  return 'done';
}

const gen = numberGenerator();

console.log(gen.next()); // 'Starting', { value: 1, done: false }
console.log(gen.next()); // 'After first yield', { value: 2, done: false }
console.log(gen.next()); // 'After second yield', { value: 3, done: false }
console.log(gen.next()); // 'Ending', { value: 'done', done: true }
console.log(gen.next()); // { value: undefined, done: true }

Resources

MDN - Generator

docs

JavaScript.info - Generators

article
Previous
Explain JavaScript's prototype chain and how inheritance works.
Next
What are Proxies in JavaScript and how can they be used?