JavaScript Iterators

Beginner
6 min read
Updated: Nov 2026

Definition and Usage

An iterable has Symbol.iterator that returns an iterator. An iterator has next() returning { value, done }. for...of, spread, and many APIs consume iterables.

JavaScript Syntax

JavaScript
const it = [10, 20][Symbol.iterator]();
console.log(it.next().value);
console.log(it.next().value);
console.log(it.next().done);
Try it Editor

How It Works

  1. Get iterator. From the array.
  2. next. Yields values until done.

Examples

Example 1 — Custom iterable

Implement the protocol.

JavaScript
const range = {
  from: 1, to: 2,
  [Symbol.iterator]() {
    let n = this.from;
    const last = this.to;
    return {
      next() {
        if (n <= last) return { value: n++, done: false };
        return { value: undefined, done: true };
      }
    };
  }
};
console.log([...range].join(","));
Try it Editor

How It Works

  1. Symbol.iterator returns next().
  2. Spread consumes it.

Example 2 — for...of

Everyday consumption.

JavaScript
for (const n of new Set([1, 1, 2])) console.log(n);
Try it Editor

How It Works

  1. Set is iterable.

Example 3 — Async iterators

Use for await...of.

JavaScript
console.log("async iterables use Symbol.asyncIterator");
Try it Editor

How It Works

  1. See for await...of and async generators.

Frequently Asked Questions

No. Arrays are iterables. Iterators are the objects that produce values via next().
Generators are a convenient way to create iterators.

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful