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:

Next, we add a one to it:

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

The process repeats on and on:

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`.

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:

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:

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:

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.