Skip to main content
FREE Mock interview & resume review with Sumit. Free right now, no payment needed.Book a slot

Iterators & Generators — JavaScript interview guide

16 / 23Language EssentialsLow priorityMedium 15 min

Iterators & Generators

An iterator gives values one by one. A generator function (function*) can pause with yield and resume later.

See it run

Press Play, or step with Next. Watch the highlighted line, the Call Stack and memory change together.

A generator pauses at yield and resumes on next()

Execution phaseStep 1/7
script.js
1function* ids() {
2 let id = 1;
3 while (true) {
4 yield id++;
5 }
6}
7
▶const gen = ids();
9console.log(gen.next().value);
10console.log(gen.next().value);
Call Stack
last in, first out
Globalrunning
Memory / Scope
Global
genGenerator { ids }
ids() — not started

no variables

Console

nothing printed yet

What happens:Calling ids() does NOT run its body. It just returns a generator object, paused before line 2.

Tip: click the box and use ← → keys to step, space to play.

Explained simply

Generators

Each call to next() runs until the next yield.

function* ids() {
  let id = 1;
  while (true) yield id++;
}
const gen = ids();
gen.next().value; // 1
gen.next().value; // 2

Remember this

  • for...of works on anything with Symbol.iterator.
  • Generators are lazy: values are produced on demand.

Interview questions

What makes an object iterable?

It has a [Symbol.iterator]() method that returns an object with a next() method returning { value, done }.

Practice

  1. Make a range(start, end) object usable in for...of.

Keep learning