Custom Iterator in JavaScript

Level 5261 keystrokes

Custom iterators implement Symbol.iterator to make objects work with for...of loops.

JavaScript code

// Create an object that can be iterated
1const range = {
// Define the range boundaries
2 from: 1,
3 to: 5,
// Symbol.iterator makes the object iterable
4 [Symbol.iterator]() {
// Return an iterator object
5 return {
// Iterator state
6 current: this.from,
7 last: this.to,
// next() is called on each iteration
8 next() {
// Check if there are more values
9 if (this.current <= this.last) {
// Return the current value and increment
10 return { done: false, value: this.current++ };
11 }
// Signal iteration is complete
12 return { done: true };
13 }
14 };
15 }
16};
17
// for...of uses the iterator automatically
18for (const n of range) console.log(n);

Output

1
2
3
4
5
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this JavaScript code and how often they appear.

  • :× 7
  • .× 7
  • {× 7
  • }× 7
  • ,× 5
  • ;× 5
  • (× 5
  • )× 5
  • +× 2
  • =× 2

More JavaScript examples at level 5

← JavaScript typing practice