How to Create Custom Iterator in JavaScript: Simple Guide
To create a custom iterator in JavaScript, define an object with a
Symbol.iterator method that returns an iterator object. This iterator object must have a next() method returning an object with { value, done } properties to control iteration.Syntax
A custom iterator requires an object with a Symbol.iterator method. This method returns an iterator object that has a next() method. The next() method returns an object with two properties: value (the current item) and done (a boolean indicating if iteration is finished).
Symbol.iterator: special key to make an object iterable.next(): method called on each iteration step.{ value, done }: object describing the current iteration state.
javascript
const iterableObject = { [Symbol.iterator]() { return { next() { return { value: 'item', done: true }; } }; } };
Example
This example creates a custom iterator that returns numbers from 1 to 3. Each call to next() returns the next number until done is true.
javascript
const customIterable = { [Symbol.iterator]() { let count = 1; return { next() { if (count <= 3) { return { value: count++, done: false }; } else { return { value: undefined, done: true }; } } }; } }; for (const num of customIterable) { console.log(num); }
Output
1
2
3
Common Pitfalls
Common mistakes include forgetting to return an object with value and done from next(), or not marking done as true to end iteration. Also, not using Symbol.iterator means the object won't work with for...of.
javascript
const wrongIterable = { next() { return 1; // Wrong: should return an object with value and done } }; const correctIterable = { [Symbol.iterator]() { let i = 0; return { next() { if (i < 2) { return { value: i++, done: false }; } else { return { value: undefined, done: true }; } } }; } };
Quick Reference
| Part | Description |
|---|---|
| Symbol.iterator | Method that returns the iterator object |
| next() | Method returning { value, done } for each iteration |
| value | Current item in iteration |
| done | Boolean indicating if iteration is finished |
Key Takeaways
Define a Symbol.iterator method that returns an object with a next() method.
The next() method must return an object with value and done properties.
Set done to true to signal the end of iteration.
Without Symbol.iterator, the object won't work with for...of loops.
Always return an object from next(), not just a value.