If you ever encountered yourself doing some practice on recursion, I’m quite sure you faced the Fibonacci sequence algorithm. If you are not familiar with this problem, take a look at what Wikipedia has to say about it:

In mathematics, the Fibonacci numbers, commonly denoted Fn, form a sequence called the Fibonacci sequence, such that each number is the sum of the two preceding ones.

So, if we start with 0 and 1, this is how the first N Fibonacci numbers look like:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...

As you can see, each number (apart from the first two) is derived from the sum of the previous 2. For example, 13 is the result of adding 8 and 5.

In this article, we will develop a solution in Javascript using recursion, and we will improve its performance using closures.

First solution

Let’s try to code a function that will receive a number n, and will retrieve the Fibonacci number at the n position. We will use the recursive approach:

function fibonacci(n) {
  if (n <= 0) {
   return 0;
  } else if (n <= 2) {
   return 1;
  }
  return fibonacci(n - 1) + fibonacci(n - 2);
}

(Note that some theories omit the first 0 from the Fibonacci sequence, in which case all you have to do is to omit the first if statement and change the second one to be n < 2 )

#memoization #fibonacci #javascript #recursion #closure

Improving the performance of the recursive Fibonacci implementation using closures
1.45 GEEK