Skip to the page

Symbols, iterators, generators and Proxy · mid

Symbols and the iteration protocol

A Symbol is a unique primitive used as a collision-free property key and as a hook into language behaviour (Symbol.iterator, Symbol.toPrimitive, Symbol.asyncIterator); an object is iterable when its Symbol.iterator returns an iterator whose next() gives { value, done }.

The notes

What you must know

  • Symbol('desc') is always unique. Symbol.for('key') returns the same symbol for the same key from a global registry.
  • Symbol keys are skipped by for...in, Object.keys and JSON.stringify, but Object.getOwnPropertySymbols and Reflect.ownKeys reveal them, so they are not private.
  • Well-known symbols: Symbol.iterator (for...of, spread), Symbol.asyncIterator (for await), Symbol.toPrimitive, Symbol.hasInstance, Symbol.toStringTag.
  • Iterable protocol: objSymbol.iterator returns an iterator. Iterator protocol: next() returns { value, done }; an optional return() runs when a consumer stops early (break, destructuring, an exception).
  • Consumers: for...of, spread, destructuring, Array.from, new Map/Set, Promise.all and yield*.
  • Arrays, strings, Map, Set, arguments and NodeList are iterable. Plain objects are not (use Object.entries).
  • ES2025 iterator helpers (map, filter, take, drop, flatMap, reduce, toArray, some, every, find, Iterator.from) are lazy: they pull one value at a time.

The red pen

Common traps: mistake → fix

  • Mistake: Symbols make properties private

    Fix: getOwnPropertySymbols lists them.

  • Mistake: for...of works on plain objects

    Fix: it throws TypeError: not iterable.

  • Mistake: An iterator can be reused

    Fix: most iterators are single-use; an iterable creates a fresh iterator each time.

Easy to hard

Questions interviewers ask, easy to hard

  1. What are Symbols for?
  2. What makes an object iterable? Make a Range object iterable.
  3. Why doesn't for...of work on a plain object?
  4. What does return() on an iterator do when you break out of a loop?
  5. What are iterator helpers and why are they lazy?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview