What is Symbol.iterator and Why is it Needed
Symbol.iterator is a special symbol used in JavaScript to create iterable objects, i.e. those that can be iterated with for...of, spread operator (...), or used in other cases where an iterable interface is required.
Iterable Objects
Objects that have a method with Symbol.iterator key are considered iterable. These are:
- arrays
[] - strings
"hello" - sets
Set - maps
Map arguments- and other built-in collections
Example:
const arr = [1, 2, 3];
for (const value of arr) {
console.log(value); // 1, 2, 3
}
Here arr[Symbol.iterator] is automatically called in for...of.
How Symbol.iterator Works
The Symbol.iterator method must return an iterator object that has a next() method.
This method returns an object with two properties:
value— current valuedone— boolean indicating if iteration is complete
Custom Iterator Example
const customIterable = {
data: [10, 20, 30],
[Symbol.iterator]() {
let index = 0;
return {
next: () => {
if (index < this.data.length) {
return { value: this.data[index++], done: false };
} else {
return { done: true };
}
}
};
}
};
for (const num of customIterable) {
console.log(num); // 10, 20, 30
}
Why Can't You Iterate Regular Objects?
const obj = { a: 1, b: 2 };
for (const key of obj) {
// TypeError: obj is not iterable
}
Objects by default are not iterable because they don't have a [Symbol.iterator] method.
To make an object iterable, you need to explicitly define this method.
Where Symbol.iterator is Used
for...ofspread (...)Array.from()Promise.allSetMapdestructuring: [...something]
Conclusion
Symbol.iteratoris the key to iterability.- Any object implementing
[Symbol.iterator]can be used infor...of. - You can create your own data structures supporting iteration according to your scenario.
Fact:
Symbol.iterator is what makes constructs like for...of, ...spread, and even yield* in generators possible.