Fibonacci JavaScript sequence for developers

All of the developers have encountered Fibonacci JavaScript sequence at least once in their in their life.
This is just like a tricky game which we play with our brains.
Whether you are a learner or a JavaScript expert, you must know Fibonacci JavaScript sequence.
That is why, we are here to explain Fibonacci concept in JavaScript programming language.
If you are already aware of this concept, you must read this out in order to have a refresher.

fibonacci

What is Fibonacci sequence?

First of all, we would like to explain what Fibonacci sequence is.
This is a sequence which is characterized by statement that every number which comes after the first two numbers will be the sum of next two preceding numbers.
This sequence is named after an Italian mathematician.

Fibonacci sequence and JavaScript:

Now, if you want to work on Fibonacci sequence through JavaScript, you can adopt two methods.
One with the help of a loop and other one with recursion method.
Now, we are going to discuss these two methods to make it easier for you to grab these two concepts.

Looping version:

The first method on which we are going to focus is loop method.

var looping = function(n) {
    var a = 0, b = 1, f = 1;
    for(var i = 2; i <= n; i++) {
        f = a + b;
        a = b;
        b = f;
    }
    return f;
};

As we have mentioned above, this sequence is the sum of previous two numbers in the sequence.
Because of this reason, we have started our loop at the index of two.
We can say that this is actually the third value as the index basically starts at zero.
Each loop iteration in this code is adding the previous two values of the code.
Once we get our desired number, we always have an option to return the new value.

Recursive version:

Now, we are going to explain the Recursive version.
You can use the following code in order to work on this method:

var recursive = function(n) {
    if(n <= 2) {
        return 1;
    } else {
        return this.recursive(n - 1) + this.recursive(n - 2);
    }
};

In the following code, the developer will get a sequence value at five.
According to our code, as soon as n <= 2, we will just return the value of one.
This is how we can use Fibonacci sequence in JavaScript.

AUTHOR

READ NEXT

Boostlog is an online community for developers
who want to share ideas and grow each other.

Delete an article

Deleted articles are gone forever. Are you sure?