JavaScript - Fibonacci series Using Recursion

Using Recursion

Recursion is another method of generating the Fibonacci series. The exponential temporal complexity of this method makes it less efficient for big n, but it is more elegant.

function fibo(n) {

    if (n <= 1) {

        return n;

    }

    return fibo(n - 1) +fibo(n - 2);

}

// Example: Generate the first 10 Fibonacci numbers using recursion

let fib_Num = [];

for (let i = 0; i < 10; i++) {

    fib_Num.push(fibo(i));

}

console.log(fib_Num);

 

In this code:

The n-th Fibonacci number is returned by the recursive function fibo(n), which we define.

The function returns n (base cases) if n is 0 or 1.

If not, the sum of the preceding two Fibonacci numbers is returned.

The first ten Fibonacci numbers are created using a loop, and they are then saved in an array.