Iterable Protocol in JavaScript: What It Is and How It Works
iterable protocol in JavaScript is a way objects can define how they are looped over using for...of loops or other iteration methods. An object is iterable if it has a Symbol.iterator method that returns an iterator, which produces values one at a time.How It Works
The iterable protocol lets JavaScript objects describe how to produce a sequence of values, one after another. Think of it like a playlist of songs: the playlist (the iterable) knows how to give you the next song when you ask for it.
To be iterable, an object must have a special method named Symbol.iterator. This method returns an iterator, which is like a helper that keeps track of where you are in the sequence and gives you the next value each time you ask.
This protocol allows JavaScript to use for...of loops, spread syntax, and other features on many types of objects, not just arrays.
Example
This example shows a simple object that follows the iterable protocol by defining Symbol.iterator. It returns numbers from 1 to 3 one by one.
const myIterable = { [Symbol.iterator]() { let current = 1; const last = 3; return { next() { if (current <= last) { return { value: current++, done: false }; } else { return { value: undefined, done: true }; } } }; } }; for (const num of myIterable) { console.log(num); }
When to Use
Use the iterable protocol when you want to create custom objects that can be looped over easily with for...of or spread syntax. This is helpful when you have a collection or sequence that isn't a simple array but you want to provide a clean way to access its items one by one.
For example, you might create an iterable for a range of numbers, a stream of data, or a custom data structure like a tree or graph.
Key Points
- An object is iterable if it has a
Symbol.iteratormethod. - The
Symbol.iteratormethod returns an iterator with anext()method. - The
next()method returns an object withvalueanddoneproperties. - Iterables work with
for...of, spread syntax, and other iteration features.