Generators & Iterators — JavaScript

A generator is a function that can stop in the middle. It is written with function* and gives values with yield. Calling it gives a generator object, and its…

At a bank, the clerk calls queue numbers one at a time: "Number 12", waits until that person has been served, then "Number 13". The clerk doesn't shout every number at once and go home.

A normal function works like a clerk who shouts every number at once: it runs from start to finish in one call. A generator is a function that works like the bank clerk who calls one number at a time. It can give one value, stop at that point, and continue from there when it is asked again. Each value is like one queue number.

A first generator: function* and yield

This example makes the generator fruits(), then asks it for two values:

function* fruits() {
  yield 'Apple'
  yield 'Mango'
  yield 'Orange'
}

const gen = fruits()
console.log(gen.next()) // { value: 'Apple', done: false }
console.log(gen.next()) // { value: 'Mango', done: false }

The first call runs as far as yield 'Apple'. The second call continues from there and stops at yield 'Mango'.

next() until done: true

If you keep calling next(), the generator is used up after the last yield:

const g = fruits()
console.log(g.next().value, g.next().value) // Apple Mango
g.next()                                     // { value: 'Orange', done: false }
console.log(g.next())                        // { value: undefined, done: true }

Getting everything: spread and for...of

This example makes a generator that counts from one number to another, then gets all of its values in two ways:

function* count(from, to) {
  for (let i = from; i <= to; i++) {
    yield i
  }
}

console.log([...count(1, 3)]) // [1, 2, 3]

for (const n of count(1, 3)) {
  console.log(n) // 1, then 2, then 3
}

Remember, calling a generator gives you a generator object, not an array. When your function has to return an array, spread the generator inside a normal function:

function list(from, to) {
  return [...count(from, to)]
}

console.log(list(2, 4)) // [2, 3, 4]

Iterators: the rule behind for...of

An object that has a next() method and gives { value, done } is called an iterator. for...of and spread work by this rule: they call next() until done: true. Generators follow the rule automatically. Arrays and strings can give you an iterator when asked:

const it = ['a', 'b'][Symbol.iterator]()
console.log(it.next()) // { value: 'a', done: false }

[Symbol.iterator]() is the method that asks an array for an iterator. Symbol.iterator is a special name built into JavaScript, so it is written inside square brackets. An object that has this method is called an iterable, and any iterable can be used in for...of.

⚠️ Generators that don't run, are used up, or never finish

TL;DR: A generator is a function that can stop in the middle. It is written with function* and gives values with yield. Calling it gives a generator object, and its body does not run yet. Each next() runs up to the next yield, then gives { value, done }: the value, and whether the generator is used up. After the last yield the result is { value: undefined, done: true }. Spread [...gen] and for...of take every value at once. Need an array? Write return [...generator()] inside a normal function. An iterator is an object with a next() method, and every generator is an iterator automatically.

⚡ The star and yield

Write:

function* fruits() {
  yield 'Apple'
  yield 'Mango'
  yield 'Orange'
}

const gen = fruits()
gen.next() // { value: 'Apple', done: false }
Guess first: has the line const gen = fruits() run the function's body yet?

Not at all. What you get is a generator object. The body only runs when next() is called.

Meaning: The star after function makes the function a generator: a function that can stop in the middle. yield gives one value, then pauses. next() continues to the next yield, then gives { value, done }: value is the value, and done says whether the generator is used up.

⚡ Used up after the last yield

Write:

g.next() // { value: 'Orange', done: false }
g.next() // { value: undefined, done: true }

Meaning: g is a generator from fruits(), and next() has already been called on it twice. The first line reaches the third yield, the last one. Once the three yields are used up, the result is { value: undefined, done: true }, and it stays that way on later calls. A generator that is used up can't start again. Need to begin again? Call fruits() once more.

⚡ Take everything at once

Write:

function* count(from, to) {
  for (let i = from; i <= to; i++) {
    yield i
  }
}

[...count(1, 3)] // [1, 2, 3]

Meaning: The spread [...count(1, 3)] keeps calling next() until done: true, then collects every value into an array. for...of does the same, one value per round. Calling a generator gives a generator object, not an array. So when you need an array, write return [...count(from, to)] inside a normal function.

What you will learn