Skip to content
Home » Program to Generate Fibonacci Sequence using a Generator Function in JavaScript

Program to Generate Fibonacci Sequence using a Generator Function in JavaScript

This program demonstrates how to use a generator function in JavaScript to generate a Fibonacci sequence. The Fibonacci sequence is a series of numbers in which each number is the sum of the two preceding ones. By utilizing a generator function, we can generate an infinite sequence of Fibonacci numbers and truncate it at a certain limit.

Code

function* fibonacci() { // a generator function
  let [prev, curr] = [0, 1];
  while (true) {
    [prev, curr] = [curr, prev + curr];
    yield curr;
  }
}

for (const n of fibonacci()) {
  console.log(n);
  // truncate the sequence at 1000
  if (n >= 1000) {
    break;
  }
}

Code Explanation

The provided code snippet defines a generator function called fibonacci(). Inside the function, it initializes two variables prev and curr with the initial values of 0 and 1 respectively.

Using a while loop with the condition true, it continuously generates the Fibonacci numbers. Within each iteration, it updates the values of prev and curr by swapping them and assigning the sum of the previous and current values to curr.

The line yield curr is used to pause and return the current Fibonacci number as an output of the generator function.

Outside the function, a for...of loop is used to iterate over the Fibonacci sequence generated by the fibonacci() generator. In each iteration, the current Fibonacci number (n) is logged to the console using console.log(n).

To limit the sequence and ensure that it doesn’t continue indefinitely, an if condition is added inside the loop. If the current Fibonacci number (n) exceeds or equals 1000, the loop is terminated using the break statement.

This program will generate and print the Fibonacci sequence until the number exceeds or equals 1000.

Example:


function* fibonacci() { // a generator function
  let [prev, curr] = [0, 1];
  while (true) {
    [prev, curr] = [curr, prev + curr];
    yield curr;
  }
}

for (const n of fibonacci()) {
  console.log(n);
  // truncate the sequence at 1000
  if (n >= 1000) {
    break;
  }
}

The above code will output:

1
1
2
3
5
8
13
21
34
55
89
144
233
377
610
987

In this example, the fibonacci() generator function is used to generate the Fibonacci sequence. The for...of loop is used to iterate over the generated sequence and log each number to the console. The sequence is truncated at 1000 using the break statement.

By understanding and implementing this code, you can generate Fibonacci sequences efficiently using generator functions in JavaScript.

Also checkout the following codes.


“Program to Generate Random Numbers in JavaScript”
How to Use XMLHttpRequest to Fetch Data from an API