Iterables & the Iteration Protocol

Look under the hood of a for...of loop to see how JavaScript uses Symbol.iterator and next() to loop over data.

JavaScript6 min readConcept 11 of 62

What makes something 'Iterable'?

Why does a for...of loop work on Arrays and Strings, but crash if you try to run it on a standard Object?

In JavaScript, an object is only 'iterable' if it implements the Iterable Protocol. This means it must have a special method attached to it using a unique key called Symbol.iterator.

The Iterator Protocol

When a for...of loop starts, it looks for the Symbol.iterator method on the object and calls it. This method returns an 'Iterator'.

An Iterator is simply an object with a next() method. Every time the loop needs a new value, it calls iterator.next().

The next() method returns an object with two properties: value (the data) and done (a boolean). The loop keeps calling next() and reading the value until done is true.

Manually iterating

You usually let for...of handle this automatically, but you can do it manually! First, get the iterator: const it = array[Symbol.iterator]().

Then, call it: it.next() might return { value: 'apple', done: false }. Call it again: it.next() returns { value: undefined, done: true }.

This protocol is what allows modern JavaScript features like the spread syntax (...) and destructuring to work seamlessly across different data types.

Manual Iteration

Step through an array manually by calling .next() on its iterator to see exactly what the for...of loop does behind the scenes.

Manual Iteration

const arr = ["🍎", "🍌"];
// 1. Get the iterator object from the array
const it = arr[Symbol.iterator]();
// 2. Manually call next() to consume values
console.log(it.next());
console.log(it.next());
console.log(it.next());
Console Output
(Click button to call next)
iWhen done becomes true, the for...of loop knows to stop automatically. Notice how the final value is undefined!

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1What two properties must the object returned by an Iterator's `next()` method contain?
  2. 2Which special key is used to define the method that makes an object iterable?
  3. 3Why will a `for...of` loop crash if used on a standard plain object?

Remember this

  • An object is 'iterable' if it has a method at Symbol.iterator.
  • The iterator method must return an object with a next() method.
  • next() must return an object shaped like { value: any, done: boolean }.
  • for...of, spread syntax, and destructuring all rely on this exact protocol behind the scenes.

Done with this concept?

Mark it complete to track your progress. No login needed.