Approach 3 Using Generator Function

Using a generator function, Fibonacci numbers are yielded incrementally. It maintains two variables representing the current and previous Fibonacci numbers. With each iteration, the next Fibonacci number is calculated and yielded, allowing for efficient memory usage and on-demand generation of the series.

Example:

JavaScript
function* fibonacciGenerator(num) {
    let num1 = 0;
    let num2 = 1;
    yield num1;
    yield num2;
    for (let i = 3; i <= num; i++) {
        let sum = num1 + num2;
        num1 = num2;
        num2 = sum;
        yield num2;
    }
}

function fibonacci(num) {
    let result;
    const iterator = fibonacciGenerator(num);
    for (let i = 0; i < num; i++) {
        result = iterator.next().value;
    }
    return result;
}

console.log("Fibonacci(5): " + fibonacci(5));
console.log("Fibonacci(8): " + fibonacci(8));

Output
Fibonacci(5): 3
Fibonacci(8): 13




JavaScript Program to print Fibonacci Series

The Fibonacci sequence is the integer sequence where the first two terms are 0 and 1. After that, the next term is defined as the sum of the previous two terms.

The sequence Fn of Fibonacci numbers is defined by the recurrence relation:

Fn = Fn-1 + Fn-2 with seed values F0 = 0 and F1 = 1

Examples:

Input : 5 
Output : 8
Input :8
Output :34

There are three methods to print the Fibonacci series, which are described below:

Table of Content

  • Approach 1: Using For loop
  • Approach 2: Using While loop
  • Approach 3: Using Recursion
  • Approach 3: Using Generator Function:

Similar Reads

Approach 1: Using For loop

Example: This example uses for loop to print the Fibonacci series....

Approach 2: Using While loop

Example: This example uses a while loop to print the Fibonacci series....

Approach 3: Using Recursion

As we know that the nth Fibonacci number is the summation of n-1 and n-2 term and the n-1 term is the summation of n-2 and n-3 terms. So, to get the nth Fibonacci term we can follow fib(n)=fib(n-1)+fib(n-2) fib(n)=fib(n-2)+fib(n-3)+fib(n-3)+fib(n-4) …. fib(n)=fib(1)+fib(0)+fib(1)+fib(0)+fib(1)+fib(0)….fib(1)+fib(0) [terms containing sum of fib(1) and fib(0) fib(1)=0 fib(2)=1...

Approach 3: Using Generator Function:

Using a generator function, Fibonacci numbers are yielded incrementally. It maintains two variables representing the current and previous Fibonacci numbers. With each iteration, the next Fibonacci number is calculated and yielded, allowing for efficient memory usage and on-demand generation of the series....