Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Iterators and generators

An iterator exposes successive results through next(), while an iterable supplies an iterator through Symbol.iterator. A generator makes both mechanisms easier to implement using function* and yield.

Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support

Syntax

iterator.next() // { value, done }
iterable[Symbol.iterator]() // iterator
function* name() { yield value; }

An iterator is an object with a next() method that returns a result object, not the element itself. An iterable exposes a [Symbol.iterator]() method that returns an iterator. Having next() alone therefore does not make an object usable in for...of.

The iterator result — iterator result value/done — is described by value and done. With done: false, value contains the next element. With done: true, iteration has finished and value may contain a final return value. Missing done is treated as false; missing value produces undefined. Do not detect completion by comparing value with undefined: that can be a valid element.

Calling a function* function creates a generator that is both an iterator and an iterable. next() resumes execution, yield supplies an element and suspends the function, and return finishes it. for...of and spread syntax ... ignore the value of the result with done: true.

A generator retains state: reusing it does not restart iteration. Call the generator function again for a fresh traversal. The example distinguishes elements from yield from the final value from return.

Examples

function* numbers() {
  yield 10;
  yield 20;
  return 99;
}

const iterator = numbers();
for (let i = 0; i < 4; i++) {
  const { value, done } = iterator.next();
  console.log(`${String(value)} | ${done}`);
}
console.log([...numbers()].join(", "));

Result

10 | false
20 | false
99 | true
undefined | true
10, 20

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources