Custom Iterator Protocol in JavaScript

Level 5245 keystrokes

Implementing Symbol.iterator allows custom objects to be used with for-of loops and spread operator.

JavaScript code

// Create range object with iterator
1const range = {
// Define start value
2 start: 1,
// Define end value
3 end: 5,
// Implement the iterator protocol
4 [Symbol.iterator]() {
// Initialize current to start
5 let current = this.start;
// Store end value
6 const end = this.end;
// Return iterator object
7 return {
// next() returns iteration result
8 next() {
// If current is within range
9 if (current <= end) {
// Return value and increment
10 return { value: current++, done: false };
11 }
// Signal iteration complete
12 return { done: true };
13 }
14 };
15 }
16};
// The spread operator calls the iterator until done: [1, 2, 3, 4, 5]
17console.log([...range]);

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
  • (× 4
  • )× 4
  • =× 4
  • ,× 3
  • [× 2

More JavaScript examples at level 5

← JavaScript typing practice