Generator Function in JavaScript

Level 4242 keystrokes

Generator functions produce values on demand using yield, enabling lazy iteration.

JavaScript code

// Generator function declared with function*
// Produces numbers from start to end
1function* range(start, end) {
// Loop through the range
2 for (let i = start; i <= end; i++) {
// yield pauses execution and returns the value
3 yield i;
4 }
5}
// Create a generator instance
6const gen = range(1, 5);
// next() resumes and gets the next yielded value
7console.log(gen.next().value);
8console.log(gen.next().value);
// Spread runs a new generator to the end and collects its values
9console.log([...range(1, 3)]);
// for...of iterates through all yielded values
10for (const n of range(4, 6)) console.log(n);

Output

1
2
[ 1, 2, 3 ]
4
5
6
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.

  • (× 12
  • )× 12
  • .× 11
  • ;× 8
  • ,× 4
  • =× 3
  • {× 2
  • }× 2
  • +× 2
  • [× 1

More JavaScript examples at level 4

← JavaScript typing practice