Skip to content
masterclassBuddyTech Buzz5 fresh blogs · 5:00 AM IST

JS Puzzles · Const

Iterator protocol

The iterator protocol standardizes objects that produce sequence values through next(). Each call returns an IteratorResult with value and done, while the iterable protocol lets language constructs obtain the iterator.

How it works

An iterator is an object whose next() method produces a sequence one result at a time. Each result uses value for the current item and done to indicate completion; an iterable exposes [Symbol.iterator]() so iteration constructs can obtain that iterator.

Syntax

iterator.next(value?)

Parameters

NameTypeDescription
valueanyAn optional value passed to next(); the protocol permits zero or one argument.

Returns

next() returns an IteratorResult object containing value and done.

Key points

  • The protocol supports both finite and unbounded sequences.
  • An iterator must provide next(), which advances the sequence.
  • next() accepts zero or one argument and returns an IteratorResult object.
  • done: false signals that the result contains another produced value.
  • done: true signals that iteration has completed.
  • value carries the current item, or can represent the iterator's final return value when completion is reported.

Common mistakes

  • Calling next() advances and consumes a typical iterator; do not assume a second loop starts from the beginning.
  • Once finished, next() should keep reporting done: true rather than producing more values.
  • Implementing next() alone does not make an object usable by for...of; it also needs the iterable protocol when a construct expects an iterable.

Example: A self-iterating counter

const counter = {
  current: 1,
  next() {
    return this.current <= 3
      ? { value: this.current++, done: false }
      : { value: undefined, done: true };
  },
  [Symbol.iterator]() {
    return this;
  }
};

for (const value of counter) console.log(value);

The object is both an iterator and an iterable: next() supplies IteratorResult objects, while [Symbol.iterator]() returns the iterator used by for...of.

When to use it

Custom iteration

Implement a custom object whose values can be consumed with for...of.

Manual traversal

Read a sequence manually when explicit control over advancement is needed.

Lazy sequences

Represent lazy or potentially infinite data without creating all values up front.

  • Iterable protocol
  • IteratorResult
  • Symbol.iterator
  • for...of
  • Generators

Source: Iteration protocols. Checked 2026-10-15.