User Defined Iterators
HardIn plain terms
Iterators allow custom iteration via the iterator protocol. An object with a next() method that returns { value, done }. Used by for...of. Implement Symbol.iterator for custom iteration.
What you need to know
- •Iterator protocol: next() returns { value, done }
- •Symbol.iterator
- •Enables for...of
Try it yourself
Copy the code below and run it in your browser console or a code editor:
const range = {
from: 1,
to: 3,
[Symbol.iterator]() {
let current = this.from;
return {
next: () => ({
value: current,
done: current++ > this.to
})
};
}
};
for (const n of range) {
console.log(n); // 1, 2, 3
}Learn more
Dive deeper with these trusted resources: