Recursive Fibonacci

The fibonacci function can be written as follows:

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

In the preceding code, we have the base cases ({1} and {2}) and the logic to compute the Fibonacci for n > 2 ({3}).

If we try to find the fibonacci(5), the following will be the result of the calls that are made:

Get Learning JavaScript Data Structures and Algorithms - Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.