Course contentsShow
← JavaScript
Lesson 2008 of 2,72342. Iteration Protocols Deep DiveFree lesson

What Symbol.iterator Provides

Symbol.iterator is a well-known symbol that returns an iterator object, enabling for...of loops and spread syntax.

What Symbol.iterator Provides

You'll learn how Symbol.iterator enables objects to work with JavaScript's iteration features like for...of loops and the spread operator.

The Core Idea

Symbol.iterator is a special well-known symbol that acts as a key on objects. When an object has a method at this key, that method returns an iterator object, which defines how to traverse through the object's values step-by-step. This is what makes arrays, strings, maps, and sets work with for...of loops and spread syntax (...).

Think of Symbol.iterator as a universal "how to loop through me" instruction manual that JavaScript knows to look for.

How It Connects Everything

When you write for (const item of myArray), JavaScript automatically:

  1. Looks for a method at myArray[Symbol.iterator]
  2. Calls that method to get an iterator object
  3. Uses the iterator to retrieve values one at a time
const arr = ['a', 'b', 'c'];

// Manually accessing what for...of does automatically
const iterator = arr[Symbol.iterator]();
console.log(iterator.next()); // { value: 'a', done: false }
console.log(iterator.next()); // { value: 'b', done: false }
console.log(iterator.next()); // { value: 'c', done: false }
console.log(iterator.next()); // { value: undefined, done: true }

The same mechanism powers the spread operator:

const letters = ['a', 'b', 'c'];
const copy = [...letters]; // Uses Symbol.iterator under the hood

Key Takeaway: Symbol.iterator is the protocol that allows objects to define their own iteration behavior, making them compatible with for...of, spread syntax, and other iteration-based features in JavaScript.