Generator Function in JavaScript

Level 5294 keystrokes

Generator functions use yield to pause execution and return values one at a time when next() is called.

JavaScript code

// Define a generator function with asterisk
1function* fibonacci() {
// Initialize first two Fibonacci numbers
2 let prev = 0, curr = 1;
// Infinite loop - generator pauses at yield
3 while (true) {
// Yield current value and pause
4 yield curr;
// Advance: prev becomes curr, curr becomes prev + curr
5 [prev, curr] = [curr, prev + curr];
6 }
7}
// Create generator iterator
8const fib = fibonacci();
// Get first value (1)
9console.log(fib.next().value);
// Get second value (1)
10console.log(fib.next().value);
// Get third value (2)
11console.log(fib.next().value);
// Get fourth value (3)
12console.log(fib.next().value);
// Get fifth value (5)
13console.log(fib.next().value);

Output

1
1
2
3
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.

  • .× 15
  • (× 13
  • )× 13
  • ;× 9
  • =× 4
  • ,× 3
  • [× 2
  • ]× 2
  • {× 2
  • }× 2

More JavaScript examples at level 5

← JavaScript typing practice