What does the following code output? function* fibonacci() { let [a, b] = [0, 1]; while (true) { yield a; [a, b] = [b, a + b]; } } const fib = fibonacci(); console.log([…Array(5)].map(() => fib.next().value));

JavaScript Professional Hard

JavaScript Professional — Hard

What does the following code output? function* fibonacci() { let [a, b] = [0, 1]; while (true) { yield a; [a, b] = [b, a + b]; } } const fib = fibonacci(); console.log([…Array(5)].map(() => fib.next().value));

Key points

  • The generator function yields Fibonacci numbers indefinitely
  • The spread operator `[...Array(5)]` creates an array of length 5
  • The `map` function calls `fib.next().value` 5 times
  • The correct answer matches the first 5 Fibonacci numbers

Ready to go further?

Related questions