Skip to content
dreamcode
dreamcode
Map
Iterables
Lesson 45 of 48
+15 XP on finish
JS EXPERTChapter 9 · JS Expert

The Iterator Protocol

for...of, spread and array destructuring all work through one agreement, the iterator protocol. An object is iterable when it has a [Symbol.iterator]() method that returns an iterator: an object whose next() returns { value, done }. Arrays, strings, Maps and Sets all follow it, and any class can join in. A generator method, *[Symbol.iterator](), is the shortest way to implement it.

Worked example

How it reads

  • [Symbol.iterator]() is what for...of looks for
  • next() returns done: true to say the sequence is over
  • Destructuring only pulls as many values as it needs
Cloud tip: Implementing the protocol makes your data structures feel native: every tool that loops just works.
index.js
JAVASCRIPT
real JavaScript, runs in your browser
Console
Run your code to see its output here.
YOUR TURN

Make Countdown iterable with a [Symbol.iterator] method so [...new Countdown(3)] prints [ 3, 2, 1 ].

Press Run to check your work.