Reading history

JavaScript Iterators and Generators (function*, yield)

4 min read 1 views

Learn the JavaScript iteration protocol, Symbol.iterator, custom iterables, generator functions with yield, and lazy infinite sequences.

The for...of loop works on arrays, strings, Maps and Sets, and the spread operator ... can unpack all of them. Both rely on one shared agreement called the iteration protocol. Once you know it, you can make your own objects loopable. Generator functions make this almost effortless: they pause at every yield and continue only when the next value is requested, which even allows endless sequences.

In this lesson you will learn

  • What iterables and iterators are
  • The next() method and { value, done } results
  • Making a custom iterable with Symbol.iterator
  • Writing generator functions with function* and yield
  • Lazy, infinite sequences

This lesson builds on Loops and Map and Set.

The Iteration Protocol

// for...of works on any "iterable": arrays, strings, Maps, Sets
for (const ch of "Hi!") console.log(ch);

// Making your own iterable with Symbol.iterator
const countdown = {
  from: 3,
  [Symbol.iterator]() {
    let n = this.from;
    return {
      next() {
        return n > 0 ? { value: n--, done: false } : { value: undefined, done: true };
      },
    };
  },
};
console.log([...countdown]);

// Calling next() by hand shows the iterator protocol
const it = [10, 20][Symbol.iterator]();
console.log(it.next());
console.log(it.next());
console.log(it.next());

Output

H
i
!
[ 3, 2, 1 ]
{ value: 10, done: false }
{ value: 20, done: false }
{ value: undefined, done: true }
  • An object is iterable if it has a method stored under the special key Symbol.iterator. Strings, arrays, Maps and Sets all have one.
  • That method returns an iterator: an object with a next() method. Each call returns { value, done }; done: true means there is nothing left.
  • countdown implements the protocol by hand, so [...countdown] and for...of work on it.
  • Calling next() on an array’s iterator shows exactly what for...of does behind the scenes.

Generator Functions

// A generator function pauses at each yield
function* steps() {
  yield "wake up";
  yield "study";
  yield "sleep";
}
const day = steps();
console.log(day.next().value);
console.log(day.next().value);
console.log([...steps()]);

// The same countdown, much shorter
function* countdown(from) {
  for (let n = from; n > 0; n--) yield n;
}
console.log([...countdown(5)]);

// Infinite sequences are fine because values are produced on demand
function* ids(prefix) {
  let n = 1;
  while (true) yield `${prefix}-${String(n++).padStart(3, "0")}`;
}
const studentId = ids("CSE");
console.log(studentId.next().value, studentId.next().value, studentId.next().value);

// Take the first n values from any iterable
function* take(iterable, n) {
  for (const x of iterable) {
    if (n-- <= 0) return;
    yield x;
  }
}
function* fibonacci() {
  let [a, b] = [0, 1];
  while (true) { yield a; [a, b] = [b, a + b]; }
}
console.log([...take(fibonacci(), 10)]);

Output

wake up
study
[ 'wake up', 'study', 'sleep' ]
[ 5, 4, 3, 2, 1 ]
CSE-001 CSE-002 CSE-003
[
  0, 1,  1,  2,  3,
  5, 8, 13, 21, 34
]
  • function* declares a generator. Calling it does not run the body; it returns a generator object, which is both an iterator and an iterable.
  • Each next() runs the body until the next yield, hands out that value, and pauses. Local variables keep their values between calls.
  • The generator version of countdown needs three lines instead of the manual iterator object.
  • ids contains while (true), yet the program does not freeze, because values are produced lazily, only when asked for.
  • take is itself a generator that stops after n values, letting you safely use infinite sequences such as Fibonacci numbers. return inside a generator ends it.

Where Iterables Are Used

FeatureExample
for...offor (const x of set) {}
Spread[...map.keys()]
Destructuringconst [first, second] = gen();
Array.fromArray.from(countdown(3))
Constructorsnew Set(iterable), new Map(iterable)
Promise.allAccepts any iterable of promises

Plain objects are not iterable. Loop over them with Object.keys, Object.values or Object.entries, which return arrays.

Common Mistakes

  1. Spreading an infinite generator ([...ids("X")]), which never finishes. Limit it with a helper such as take.
  2. Reusing a finished generator; once done is true it stays done. Call the generator function again for a fresh one.
  3. Using for...in on arrays, which loops over keys as strings, not values.
  4. Forgetting the asterisk, which makes yield a syntax error.

Practice Exercises

Exercise 1. Write a generator range(start, end, step) and use it to print the even numbers from 0 to 10.

Show answer
function* range(start, end, step = 1) {
  for (let i = start; i <= end; i += step) yield i;
}
console.log([...range(0, 10, 2)]);   // [0, 2, 4, 6, 8, 10]

Exercise 2. Write a generator that cycles through “red”, “amber”, “green” forever, like a traffic light, and print six steps.

Show answer
function* traffic() {
  while (true) { yield "red"; yield "amber"; yield "green"; }
}
const light = traffic();
for (let i = 0; i < 6; i++) console.log(light.next().value);

Frequently Asked Questions

Where are generators used in real projects?

For lazy data pipelines, paginated results, unique ID makers, walking tree structures and test data. Async generators (async function* with for await...of) stream data from servers piece by piece.

Is a generator the same as an async function?

No. Both can pause, but a generator pauses at yield until your code asks for the next value, while an async function pauses at await until a promise settles.

Summary

  • Iterables have a Symbol.iterator method that returns an iterator with next().
  • for...of, spread and destructuring all use this protocol.
  • function* and yield create iterators with very little code.
  • Generators are lazy, so infinite sequences are possible if you limit how many values you take.

Next: Higher-Order Functions.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *