- Home
- /
- Tutorials
- /
- JavaScript Tutorial
- /
- JavaScript Custom Iterables
JavaScript Generators & Iterators
JavaScript Custom Iterables
Adding a Symbol.iterator method makes your own object work with for...of.
Adding a
Symbol.iteratormethod makes your own object work withfor of.
This is how you plug a custom type into every language feature that expects an iterable.
A generator is the easiest way to implement it.
Example
Example
javascript
const range = {
from: 1,
to: 3,
[Symbol.iterator]: function* () {
for (let i = this.from; i <= this.to; i++) {
yield i;
}
}
};
console.log([...range].join(","));