javascript / intermediate
Snippet
Implementing Custom Iterators
By implementing the Symbol.iterator method, an object becomes 'iterable', allowing it to be used in for...of loops and with the spread operator. The method must return an object with a next() function.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const countdown = {from: 5,[Symbol.iterator]() {let current = this.from;return {next() {return current >= 0? { value: current--, done: false }: { done: true };}};}};for (const num of countdown) {console.log(num); // 5, 4, 3, 2, 1, 0}
Breakdown
1
[Symbol.iterator]() { ... }
A special built-in symbol that defines the default iterator for an object.
2
next() { ... }
The function called by the iterator to get the next item in the sequence.