Fibonacci series program in javascript using arrays, recursion, and loops (2023)

What is a Fibonacci series in the first place?

A Fibonacci series is a mathematical series wherein the last two numbers (preceding numbers) are added together to give the succeeding number in the series.

We start the counting from 0, then 1. Their sum ( 0 + 1 ) = 1 gives us the next number 1. Again the process repeats, ( 1 + 1 ) = 2 and so on…
So in the end we get the series – 0, 1, 1, 2, 3, 5, 8, 13…. to infinity.

Javascript Program

We can use recursion, loops, or arrays to write a Fibonacci series program that we can use.

Using arrays

function fibonacci(n){
    let res =[1,1]
    for (let i = 2; i < n; i++) {
        res.push(res[i-1]+res[i-2])        
    }
    return res[res.length-1]
}

Using loops

function fibo(n) {
  let seed = [1, 1];
  for (i = 1; i < n; i++) {
    seed.push(seed[i] + seed[i - 1]);
  }
  return seed[n-1];
}

Using recursion

function fibonacci(n) {
    if (n < 2) {
        return n;
    }
    // get fibonacci number (sum of previous two nums)
    return fibonacci(n - 1) + fibonacci(n - 2);
}

Conclusion

This sequence is seen in many forms all throughout nature. The use of the golden ratio is one such example. It is used in graphic design extensively, in logos, architecture design, formations, etc.

Similarly, it can be used in programming in data visualization, graphs, stats, or more.

Check out more posts in development that might interest you.