A Look At The Fibonacci Sequence: A Recursive and Iterative Solution js
The Fibonacci sequence is a famous series of numbers where each number is the sum of the two preceding ones, usually starting with 0 and 1. Here’s a look at how to implement Fibonacci in JavaScript, both with recursion and iteration.
Recursive Solution
The recursive approach to Fibonacci is straightforward, but it’s not the most efficient for large values. This function calls itself for each Fibonacci number until it reaches the base cases, fib(0) = 0
and fib(1) = 1
.
Code:
function fibonacciRecursive(n) {
if (n <= 1) return n; // Base cases
return fibonacciRecursive(n - 1) + fibonacciRecursive(n - 2);
}
console.log(fibonacciRecursive(6)); // Output: 8
Explanation:
- Time Complexity: O(2^n) — very inefficient for large values of
n
as it makes many redundant calls. - Space Complexity: O(n) — due to the call stack used in recursion.
When to Use:
The recursive solution is elegant and concise, making it a good choice for small n
values or when code readability is a priority over performance.