Fibonacci sequence in JS should not be hard to build. In this article, we show step-by-step, how to build in a few simple steps, a rudimentary Fibonacci sequence. Once we know the basic mehanism that lies behind the logic of Fibonacci sequence code, we can then build more complex code based on this foundation.

Before we write the solution for this task, we’ll first examine the Array.prototype.reduce() method in depth.

The Fibonacci sequence is a mathermatical foundation for the Golden ratio. The sequence builds up from a zero:

0

Next, we add a one to it:

0, 1

After that, the next number we get is the sum of the previous two numbers, so:

0, 1, (0 + 1)

The process repeats on and on:

0, 1, 1, (1 + 1)

Here are the first 10 digits of the Fibonacci series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34.

Now that we know what our Fibonacci function needs to produce, let’s think about how to write it.

Obviously, we start with a 0 and a 1.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function fibonacci(num) {
    let zero = 0;
    let one = 1;
    
    while(num > 0) {
        console.log(zero, one, num);
        num = num - 1;
    }
}
fibonacci(5);
/*
0 1 5
0 1 4
0 1 3
0 1 2
0 1 1
*/

Now that we’ve taken care of the count down, i.e we’ve limited the length of our sequence, the question here is, how do we keep adding the previous two numbers?

Here’s an intermediate step:

1
2
3
4
5
6
7
8
9
10
11
function fibonacci (num) {
    let arr = [];
    let zero = 0;
    let one = 1;
    while(num > 0) {
        arr.push(num);
        num = num - 1;
    }
    return arr;
}
fibonacci(5); // [5, 4, 3, 2, 1]

Now we are counting down from num to 0, and we’re pushing items into an array. That’s a progress, but we now need to push the correct items into the array. So let’s slightly alter our code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function fibonacci (num) {
    let arr = [];
    let first = 0;
    let second = 1;
    let sum;

    while(num > 0) {
        sum = first + second;
        arr.push(sum);

        num = num - 1;
    }
    return arr;
}
fibonacci(5); // [1,1,1,1,1]

The next number in our Fibonacci series will always be the sum of the previous first and second number. That’s why we’re setting the sum = first + second. There’s one thing missing here, though. That is the update of the first and second num to the newly pushed member of the array. What that means is, practically, if we’re building a Fibonacci series of 5 numbers, we’re doing this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function fibonacci (num) {
    let arr = [];
    let first = 0;
    let second = 1;
    let sum;

    while(num > 0) {
        sum = first + second;
        arr.push(sum);

        first = second;
        second = sum; 
        
        num = num - 1;
    }
    return arr;
}
fibonacci(5);
(5) [1, 2, 3, 5, 8]

Now this code works for any number of arguments.



Note:
This exercise comes from Book 3 of my book series on JS, available on Leanpub.com.