JavaScript Interview Question #125
What are iterables and iterators in JavaScript?
Closures, Prototypes, Classes & Advanced Functions Mid-Level Intermediate
Quick Interview Answer
An iterable is an object that implements the iterable protocol by providing a method at Symbol.iterator. That method returns an iterator. An iterator exposes a next method that returns objects containing value and done.
Detailed Explanation
An iterable is an object that implements the iterable protocol by providing a method at Symbol.iterator. That method returns an iterator. An iterator exposes a next method that returns objects containing value and done.
Arrays, strings, Maps, and Sets are built-in iterables, which is why they work with for...of and spread syntax. Custom objects can implement Symbol.iterator when they need to define their own sequence behavior.
Code Example
const range = {
start: 1,
end: 3,
*[Symbol.iterator]() {
for (let i = this.start; i <= this.end; i++) {
yield i;
}
}
};
for (const number of range) {
console.log(number);
}
// 1, 2, 3