The Fibonacci sequence in Javascript

The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones. The sequence starts with 1, 1 (or sometimes 0, 1).

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

Naive Recursive Approach

The most straightforward way to generate the nth Fibonacci number uses recursion:

function fibNaive(n) {
    if (n <= 1) return n;
    return fibNaive(n - 1) + fibNaive(n - 2);
}

console.log(fibNaive(7));
console.log(fibNaive(8));
console.log(fibNaive(9));
console.log(fibNaive(4));
13
21
34
3

The Problem with Naive Recursion

The naive approach has a major inefficiency. Let's visualize the function calls for f(5):

/**
 * f(5)
 *   / \
 * f(4) f(3)
 *  / \  / \
 * f(3)f(2)f(2)f(1)
 *  / \ ..........
 * f(2)f(1)..........
 */

Notice that f(2) is calculated multiple times. This creates overlapping subproblems that make the algorithm extremely slow for large values. The time complexity is O(2^n), which becomes impractical for n > 40.

Dynamic Programming Solution (Memoization)

We can optimize this by storing previously computed values to avoid redundant calculations:

let fibStore = {};

function fibDP(n) {
    if (n <= 1) return n;
    
    if (fibStore[n]) {
        return fibStore[n];
    }
    
    fibStore[n] = fibDP(n - 1) + fibDP(n - 2);
    return fibStore[n];
}

console.log(fibDP(7));
console.log(fibDP(8));
console.log(fibDP(9));
console.log(fibDP(40)); // This would be very slow with naive approach
13
21
34
102334155

Iterative Approach

An even more efficient approach uses iteration with O(1) space complexity:

function fibIterative(n) {
    if (n <= 1) return n;
    
    let a = 0, b = 1;
    for (let i = 2; i <= n; i++) {
        let temp = a + b;
        a = b;
        b = temp;
    }
    return b;
}

console.log(fibIterative(10));
console.log(fibIterative(15));
55
610

Performance Comparison

Method Time Complexity Space Complexity Best For
Naive Recursive O(2^n) O(n) Learning recursion
Memoization O(n) O(n) Multiple queries
Iterative O(n) O(1) Single calculation

Conclusion

The Fibonacci sequence demonstrates the power of dynamic programming. While the naive recursive approach is intuitive, memoization and iterative solutions provide dramatically better performance for practical applications.

Updated on: 2026-03-15T23:18:59+05:30

624 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements