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.
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
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
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.