JavaScript - Fibonacci series Using a Loop

Using a loop is the simplest method for creating a Fibonacci series. The following JavaScript method creates the Fibonacci sequence's first n numbers:

function fibo_Series(n) {

    let fib_Ser = [0, 1]; // Starting values

    for (let i = 2; i < n; i++) {

        fib_Ser[i] = fib_Ser[i - 1] + fib_Ser[i - 2];

    }

    return fib_Ser;

}

// Example: Generate the first 10 Fibonacci numbers

console.log(fibo_Series(10));

 

In this code:

The first two numbers [0, 1] initialize the Fibonacci series array.

To calculate the remaining values, we employ a for loop. Since the first two integers are already determined, the loop begins at i = 2.

The total of the two numbers that came before it, fibSeries[i - 1] + fibSeries[i - 2], equals each new number.