0
0
JavascriptComparisonBeginner · 4 min read

Generator vs Iterator in JavaScript: Key Differences and Usage

In JavaScript, an iterator is an object that provides a sequence of values via a next() method, while a generator is a special function that can pause and resume execution to produce an iterator automatically. Generators simplify creating iterators by using yield to produce values one at a time.
⚖️

Quick Comparison

This table summarizes the main differences between generators and iterators in JavaScript.

AspectIteratorGenerator
DefinitionAn object with a next() method returning {value, done}A special function that returns an iterator and uses yield to produce values
CreationManually created by defining next()Created by defining a function with function* syntax
State ManagementManual tracking of iteration stateAutomatic state management by JavaScript engine
Syntax ComplexityMore verbose and error-proneSimpler and cleaner with yield
Use CaseCustom iteration logicEasier lazy sequences and asynchronous flows
Pause/ResumeNo built-in pause, just next callsCan pause and resume execution at yield points
⚖️

Key Differences

An iterator in JavaScript is any object that implements a next() method which returns an object with value and done properties. You have to manually write the logic to keep track of the current position and decide when the iteration ends.

A generator is a special kind of function declared with function* syntax. It automatically creates an iterator object when called. Inside the generator, you use the yield keyword to pause the function and return a value. When next() is called again, the generator resumes from where it left off, making state management automatic and simpler.

Generators are more powerful because they can pause and resume execution, which is useful for lazy evaluation and asynchronous programming. Iterators are more basic and require more manual work to implement the same behavior.

⚖️

Code Comparison

Here is how you create a simple iterator manually that returns numbers from 1 to 3.

javascript
function createIterator() {
  let count = 1;
  return {
    next() {
      if (count <= 3) {
        return { value: count++, done: false };
      } else {
        return { value: undefined, done: true };
      }
    }
  };
}

const iterator = createIterator();
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());
Output
{"value":1,"done":false} {"value":2,"done":false} {"value":3,"done":false} {"value":undefined,"done":true}
↔️

Generator Equivalent

The same sequence using a generator function is simpler and cleaner.

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

const gen = numberGenerator();
console.log(gen.next());
console.log(gen.next());
console.log(gen.next());
console.log(gen.next());
Output
{"value":1,"done":false} {"value":2,"done":false} {"value":3,"done":false} {"value":undefined,"done":true}
🎯

When to Use Which

Choose an iterator when you need full control over the iteration process and want to implement custom iteration logic manually. This is useful for simple or very specific iteration patterns.

Choose a generator when you want cleaner, easier-to-read code that automatically handles iteration state and supports pausing and resuming execution. Generators are ideal for lazy sequences, complex iteration, and asynchronous flows.

Key Takeaways

Generators are special functions that automatically create iterators with simpler syntax using yield.
Iterators require manual implementation of the next() method and state tracking.
Generators can pause and resume execution, making them more powerful for complex iteration.
Use iterators for custom, manual control; use generators for cleaner, easier iteration code.
Both produce the same output but differ in ease of use and capabilities.