Intermediate JavaScript Interview QuestionsIntermediateComparison
JavaScript · Question 65
What is the difference between an iterable and an iterator in JavaScript?
Direct answer
An iterable has a Symbol.iterator method that produces an iterator; an iterator has a next() method that returns objects containing value and done, allowing consumers such as for...of and spread to pull values sequentially.
Arrays, strings, Maps, and Sets are built-in iterables. That is why operations such as for (const x of value) and [...value] can consume them.
- Iterable → implements
[Symbol.iterator](). - Iterator → implements
next()and returns results such as{value: 10, done: false}. - An iterator can also be iterable by returning itself from
[Symbol.iterator](), which makes it compatible with iterable-consuming syntax. - Plain object literals are not automatically iterable merely because they have properties; use
Object.keys/values/entriesor define an iteration protocol deliberately.
The protocol enables lazy consumption: the producer does not need to create an entire result array before the consumer starts reading values.