JavaScript recursive method to find Fibonacci sequence of numbers

Hello Guys, In this small article I am going to show you how with JavaScript recursive method to find Fibonacci sequence of numbers with very simple technique.

A small introduction to know what is a Fibonacci series. Its a sequence of number very popular. Every living organism is said to follow this principle for expanding its root.

let us start with zero (0). Everything start with zero. count 0 + 1 = 1.

Now again 1 (previous value ) + 1 (total value) = 2 (next number of sequence).

Again 1 + 2 = 3, 2 + 3 = 5, 3 + 5 = 8 and so on..

Let us now calculate the same via JavaScript recursive method to find Fibonacci sequence of numbers.

let fibonacci = function(result, len) {
  // result[0, 1]; considering result as an array
  if(result.length >= len) {return result;} // exit recursion when limit reached.
  result.push(result[result.length-2] + result[result.length-1]);
  return fibonacci(result, len);  //return function until limit is reach.
}

So the above 3 line of code without comments. Let me explain each line.

We started with a function name fibonacci with two parameters. First parameter accepts an array of starting point of fibonacci sequence which is [0, 1].

result.push(result[result.length-2] + result[result.length-1]);

This above code is doing the calculation thing. Just like the example I have simply add previous value and total value and put them at the end of array. Here I have taken the sum of second last array index and last array index and push them at the end of the array called result. After the first iteration the array result will be modified to [0,1,1], because 0 + 1 = 1. Now,

return fibonacci(result, len); 

After the athematic operation and array push method our result array will becomes result = [0,1,1]. So we have now passed the updated array in the function and return it so it will calculate again because the below condition is not meet.

if(result.length >= len) {return result;}

Our result array length was only 3 so it will continue its operation. The above if statement states that if the result array length is greater than or equals to the number of length we have provided then it will stop its execution and return the final result as an array.

console.log(fibonacci([0,1], 10));

The above function will console log sequence of Fibonacci sequence until the array length is 10.

[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

I hope its clear now. Thanks for reading.

Leave a Reply

Your email address will not be published.