Generate the Fibonacci sequence in JavaScript
Intermediate · 4 min read
The Fibonacci sequence starts with 0 and 1, and every number after that is the sum of the two before it: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34. It turns up in nature, in art and in countless coding interviews. It is also the classic example of code that looks elegant and is unusably slow.
In this tutorial you will write the Fibonacci function three ways. First the plain recursive version, fibNaive. Then you will count how much work it does and fix it with memoization in fibMemo. Finally you will write fibLoop, which needs no recursion at all. You need to know what a function and a loop are. Recursion and memoization are explained from the start.
The rule, written as code
Number the sequence from 0, so fib(0) is 0, fib(1) is 1 and fib(2) is 1. The rule is:
fib(0)is 0 andfib(1)is 1.- For anything bigger,
fib(n)isfib(n - 1) + fib(n - 2).
What recursion is
A recursive function is one that calls itself. That suits a rule like this, which defines each number in terms of smaller ones. Every recursion needs a base case, an input where it stops calling itself and just answers. Here the base cases are 0 and 1.
Here is the exercise. Try it yourself first if you like, or follow the steps.
31 Fibonacci numbers, and why the naive recursion is a trap
fairProduce the first several Fibonacci numbers. Write the plain recursion, then show why it is unusable and fix it.
Stuck? Three hints, smallest first
- 1. The naive recursion recomputes the same values exponentially many times.
- 2. Remembering answers in a
Mapturns it from exponential into linear. - 3. The loop version needs no memory at all beyond the last two values.
Step 1: the plain recursion
Translate the rule straight into code. n < 2 covers both base cases, because fib(0) is 0 and fib(1) is 1, so n is its own answer:
function fibNaive(n) {
return n < 2 ? n : fibNaive(n - 1) + fibNaive(n - 2);
}
console.log(fibNaive(10)); // 55
It reads exactly like the rule. It looks finished.
Step 2: count the calls
Add a counter that goes up every time the function runs:
let naiveCalls = 0;
function fibNaive(n) {
naiveCalls++;
return n < 2 ? n : fibNaive(n - 1) + fibNaive(n - 2);
}
fibNaive(25);
console.log(naiveCalls); // 242785
Nearly a quarter of a million calls to work out one number. Here is why. fib(25) calls fib(24) and fib(23). But fib(24) also calls fib(23). Each of those calls fib(22) again, and so on down. The same small values get worked out again and again, thousands of times each. Every time n goes up by one, the work grows by roughly 1.6 times. fibNaive(45) would need more than three billion calls.
Step 3: remember the answers
Memoization means storing the answer for each input the first time you work it out, and looking it up next time instead of recomputing it. A Map is a good place to store them: set(key, value) saves a value and get(key) reads it back, returning undefined for a key it doesn't have.
function fibMemo(n, seen = new Map()) {
if (n < 2) return n;
const cached = seen.get(n);
if (cached !== undefined) return cached;
const value = fibMemo(n - 1, seen) + fibMemo(n - 2, seen);
seen.set(n, value);
return value;
}
console.log(fibMemo(25)); // 75025
console.log(fibMemo(50)); // 12586269025
seen = new Map() is a default parameter: the first call creates a fresh Map, and every recursive call passes the same one along. So once fib(23) is known, every later request for it is a quick lookup. Each value from 2 to n is now worked out only once, and fibMemo(50) answers instantly, where fibNaive(50) would take far too long to wait for.
Step 4: walk forward with a loop
Look at how you would do this by hand. You don't need the whole sequence, only the last two numbers. Start with a = 0 and b = 1. Each step, the new pair is b and a + b:
function fibLoop(n) {
let [a, b] = [0, 1];
for (let i = 0; i < n; i++) [a, b] = [b, a + b];
return a;
}
console.log(fibLoop(0)); // 0
console.log(fibLoop(10)); // 55
console.log(fibLoop(25)); // 75025
[a, b] = [b, a + b] is destructuring. The right side builds a new pair from the current values, then the left side unpacks it into a and b. Both values are updated at once, so you don't need a temporary variable. Trace it: (0, 1), (1, 1), (1, 2), (2, 3), (3, 5)... After n steps, a holds fib(n). That is 25 steps for fib(25), with no recursion and nothing stored.
Step 5: list the first ten
Array.from({ length: 10 }, (_, i) => fibLoop(i)) builds an array of ten items, calling the function with each position from 0 to 9:
const first10 = Array.from({ length: 10 }, (_, i) => fibLoop(i));
console.log(first10.join(', ')); // 0, 1, 1, 2, 3, 5, 8, 13, 21, 34
The _ is a name for the first argument, which we don't use. join(', ') turns the array into text with a comma and space between items.
The full solution
The complete answer has all three versions, prints the first ten numbers, counts the calls fibNaive(25) makes, and checks that the memoized version agrees with the loop for the first twenty values. Press Run to see the output.
let naiveCalls = 0;
function fibNaive(n) {
naiveCalls++;
return n < 2 ? n : fibNaive(n - 1) + fibNaive(n - 2);
}
// Remember what you have already worked out.
function fibMemo(n, seen = new Map()) {
if (n < 2) return n;
const cached = seen.get(n);
if (cached !== undefined) return cached;
const value = fibMemo(n - 1, seen) + fibMemo(n - 2, seen);
seen.set(n, value);
return value;
}
// No recursion, no memory: keep the last two and walk forward.
function fibLoop(n) {
let [a, b] = [0, 1];
for (let i = 0; i < n; i++) [a, b] = [b, a + b];
return a;
}
const first10 = Array.from({ length: 10 }, (_, i) => fibLoop(i));
console.log('first ten:', first10.join(', '));
naiveCalls = 0;
fibNaive(25);
console.log('fibNaive(25) made', naiveCalls, 'calls');
console.log('fibLoop(25) is', fibLoop(25), 'with 25 steps');
Output
6 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 6 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('the first ten', first10, [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]);
test('memo agrees with the loop', Array.from({ length: 20 }, (_, i) => fibMemo(i)), Array.from({ length: 20 }, (_, i) => fibLoop(i)));
test('a larger value', fibLoop(50), 12586269025);
test('the naive version needs over 100,000 calls for n=25', naiveCalls > 100000, true);
test('memoised version is exact too', fibMemo(30), fibLoop(30));
test('fib(0) is 0', fibLoop(0), 0);
The call count is the point. fibNaive(25) makes over 240,000 calls to compute a number the loop reaches in 25 steps, because it recalculates fib(20) thousands of times. This is the standard illustration of why memoisation exists, and why "it is recursive so it must be elegant" is not an argument.
Common mistakes
- Shipping the plain recursion. It is correct and very slow. A few dozen is already too big for it.
- Creating a new Map on every call. If each recursive call made its own Map, nothing would ever be remembered. Pass the same
seenalong. - Updating
aandbone at a time.a = b; b = a + b;uses the newaby mistake. Update both together with destructuring.
Try it yourself
- Count the calls
fibMemo(25)makes, the same way Step 2 countedfibNaive. - Write
fibUpTo(limit)that returns every Fibonacci number belowlimit, for example all those below 100. - Find the first Fibonacci number bigger than
Number.MAX_SAFE_INTEGERusingfibLoop.