Loading...
Loading...
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.
Objects that have a method with Symbol.iterator key are considered iterable. These are:
[]"hello"SetMapargumentsconst 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.
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 completeconst 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
}
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.
for...ofspread (...)Array.from()Promise.allSetMapdestructuring: [...something]Symbol.iterator is the key to iterability.[Symbol.iterator] can be used in for...of.Fact:
Symbol.iterator is what makes constructs like for...of, ...spread, and even yield* in generators possible.