Fibonacci with memoization in JavaScript
Intermediate · 4 min read
The Fibonacci sequence starts 0, 1, and then each number is the sum of the two before it: 0, 1, 1, 2, 3, 5, 8, 13, 21 and so on. It appears in nature, in art, and in almost every programming course, because it is the standard example for a technique called memoization.
In this tutorial you will compute Fibonacci numbers three ways: with a simple loop, with plain recursion, and with recursion plus a cache. You will count how much work each one does, and the difference is dramatic: 242,785 function calls against 49. Then you will find the last Fibonacci number a JavaScript number can hold exactly. You need to know functions, loops and what recursion is (a function that calls itself).
What memoization means
Memoization means remembering answers you have already worked out. The first time a function is asked for a value, it computes it and stores it. The next time, it looks it up instead of computing it again. The storage is usually a Map, which holds key-value pairs:
const memo = new Map();
memo.set(10, 55);
console.log(memo.has(10)); // true
console.log(memo.get(10)); // 55
Swapping two variables
The loop version uses a short trick, [a, b] = [b, a + b]. The right side builds a two-item array from the current values, and the left side unpacks it back into a and b. Both are updated together, so you don't need a temporary variable.
Here is the exercise. Try it yourself first if you like, then read on and we will build it together.
52 Fibonacci, iteratively and memoised
fairCompute Fibonacci numbers with a loop, then count how many calls a naive recursion makes for fib(25) and how many a memoised one makes. Find the last term a double can hold exactly.
Stuck? Three hints, smallest first
- 1. Two variables and a swap are all the iterative version needs.
- 2. Naive recursion recomputes the same subtrees; the call count is
2 * fib(n + 1) - 1. - 3. Lucas numbers use the same recurrence from different seeds: 2 and 1 instead of 0 and 1.
Step 1: the loop
function fib(n) {
let a = 0;
let b = 1;
for (let i = 0; i < n; i++) [a, b] = [b, a + b];
return a;
}
console.log(Array.from({ length: 12 }, (_, i) => fib(i)).join(', ')); // 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89
console.log(fib(50)); // 12586269025
a and b are always two neighbors in the sequence. Each pass moves them one place along. After n passes, a holds the nth number. This takes n steps, so it is fast even for large n.
Step 2: plain recursion
The definition "each number is the sum of the two before" translates straight into a recursive function. We add a counter to see how many calls it makes:
let naiveCalls = 0;
function naiveFib(n) {
naiveCalls++;
return n < 2 ? n : naiveFib(n - 1) + naiveFib(n - 2);
}
console.log(naiveFib(5), naiveCalls); // 5 15
The answer is right, but 15 calls for fib(5) is a lot. The reason: naiveFib(5) calls naiveFib(4) and naiveFib(3). But naiveFib(4) also calls naiveFib(3). The same values are worked out again and again.
Step 3: watch it explode
naiveCalls = 0;
console.log(naiveFib(25)); // 75025
console.log(naiveCalls); // 242785
242,785 calls for the 25th number. There is a neat pattern here: the call count is always 2 * fib(n + 1) - 1. The count grows like the Fibonacci numbers themselves, by about 1.6 times per step. For fib(50) it would be about 40 billion calls.
console.log(2 * fib(26) - 1); // 242785
Step 4: add the memo
Now the same recursion, but it checks the Map before doing any work and stores every answer it computes:
let memoCalls = 0;
const memo = new Map();
function memoFib(n) {
memoCalls++;
if (n < 2) return n;
if (memo.has(n)) return memo.get(n);
const value = memoFib(n - 1) + memoFib(n - 2);
memo.set(n, value);
return value;
}
console.log(memoFib(25)); // 75025
console.log(memoCalls); // 49
49 calls instead of 242,785. Each value from 2 to 25 is computed once. Every other call finds its answer already in the Map and returns straight away. For n, the count is 2 * n - 1.
The loop from Step 1 is still the simplest and fastest. Memoization matters when the recursive form is the natural way to describe a problem and you can't easily turn it into a loop.
Step 5: the last exact Fibonacci number
Fibonacci numbers grow quickly, and JavaScript numbers hold whole numbers exactly only up to Number.MAX_SAFE_INTEGER. A BigInt version of the loop gives the exact values to compare against. BigInt literals end in n, like 0n.
function fibExact(n) {
let a = 0n;
let b = 1n;
for (let i = 0; i < n; i++) [a, b] = [b, a + b];
return a;
}
console.log(fib(78), Number.isSafeInteger(fib(78))); // 8944394323791464 true
console.log(fib(79)); // 14472334024676220
console.log(fibExact(79).toString()); // 14472334024676221
fib(78) is the last one inside the safe range. fib(79) is odd and past the limit. JavaScript can only store even numbers in that range, so it quietly gives you the even number just below. No error, just an answer that is 1 too small.
Step 6: same rule, different start
Start the same rule from 2 and 1 instead of 0 and 1, and you get the Lucas numbers:
function lucas(n) {
let a = 2;
let b = 1;
for (let i = 0; i < n; i++) [a, b] = [b, a + b];
return a;
}
console.log(Array.from({ length: 11 }, (_, i) => lucas(i)).join(', ')); // 2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 123
console.log(lucas(10) === fib(9) + fib(11)); // true
Each Lucas number is the sum of the Fibonacci numbers either side of the same position.
The full solution
The answer panel has the loop, the BigInt loop, the counting naive and memoized versions, and the Lucas loop, then prints the first twelve numbers, fib(50), the fib(78) and fib(79) limit, both call counts and the first eleven Lucas numbers. Press Run to see the output.
function fib(n) {
let a = 0;
let b = 1;
for (let i = 0; i < n; i++) [a, b] = [b, a + b];
return a;
}
// Same recurrence, exact, for checking where the double version drifts.
function fibExact(n) {
let a = 0n;
let b = 1n;
for (let i = 0; i < n; i++) [a, b] = [b, a + b];
return a;
}
let naiveCalls = 0;
function naiveFib(n) {
naiveCalls++;
return n < 2 ? n : naiveFib(n - 1) + naiveFib(n - 2);
}
let memoCalls = 0;
const memo = new Map();
function memoFib(n) {
memoCalls++;
if (n < 2) return n;
if (memo.has(n)) return memo.get(n);
const value = memoFib(n - 1) + memoFib(n - 2);
memo.set(n, value);
return value;
}
// Lucas: the same rule, seeded 2 and 1.
function lucas(n) {
let a = 2;
let b = 1;
for (let i = 0; i < n; i++) [a, b] = [b, a + b];
return a;
}
naiveCalls = 0;
const naive25 = naiveFib(25);
const naiveCost = naiveCalls;
memoCalls = 0;
const memo25 = memoFib(25);
const memoCost = memoCalls;
console.log('first twelve :', Array.from({ length: 12 }, (_, i) => fib(i)));
console.log('fib(50) :', fib(50));
console.log('fib(78) :', fib(78), 'safe?', Number.isSafeInteger(fib(78)));
console.log('fib(79) :', fib(79), 'but exactly', fibExact(79).toString());
console.log('naive fib(25):', naive25, 'in', naiveCost, 'calls');
console.log('memoised :', memo25, 'in', memoCost, 'calls');
console.log('lucas :', Array.from({ length: 11 }, (_, i) => lucas(i)));
Output
9 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 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('the first twelve Fibonacci numbers', Array.from({ length: 12 }, (_, i) => fib(i)), [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]);
test('fib(50) is 12586269025', fib(50), 12586269025);
test('fib(78) is the last one that is a safe integer', [fib(78), Number.isSafeInteger(fib(78)), Number.isSafeInteger(fib(79))], [8944394323791464, true, false]);
test('and fib(79) comes back one short of the true value', [fib(79), fibExact(79).toString()], [14472334024676220, '14472334024676221']);
test('the naive recursion makes 242785 calls for fib(25)', naiveCost, 242785);
test('which is exactly 2 * fib(26) - 1', 2 * fib(26) - 1, 242785);
test('memoising cuts that to 49, or 2n - 1', [memoCost, 2 * 25 - 1], [49, 49]);
test('the Lucas numbers, same rule from different seeds', Array.from({ length: 11 }, (_, i) => lucas(i)), [2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 123]);
test('and L(n) is F(n-1) + F(n+1)', Array.from({ length: 12 }, (_, i) => i + 1).every((n) => lucas(n) === fib(n - 1) + fib(n + 1)), true);
242,785 calls to compute the 25th Fibonacci number, against 49 with a Map in front and 25 iterations with a loop. The exact figure 2 * fib(n + 1) - 1 is worth knowing because it makes the cost visible: the call count is itself Fibonacci, so it grows by a factor of about 1.618 per step. fib(50) naively would be about 40 billion calls.
The precision limit is fib(78). fib(79) is 14472334024676221, which is odd and past 2 ** 53, so the nearest double is the even number below it and the loop returns a value one too small — silently, with no flag and no exception. You cannot even write the true value as a literal to compare against, which is why the check above holds it as a BigInt and compares strings. Note that BigInt values must not go into test directly: JSON.stringify throws on them.
Common mistakes
- Using plain recursion for big n. fib(50) would take about 40 billion calls. Use the loop or a memo.
- Creating the memo inside the function. A
new Map()on every call remembers nothing. Create it once, outside. - Trusting fib(79) and beyond. Past fib(78) the numbers are rounded without warning. Use BigInt for exact values.
Try it yourself
- Count the calls
naiveFib(20)makes and check it against2 * fib(21) - 1. - Write a memoized version of
lucasusing its ownMap. - Print
fibExact(100).toString(). How many digits does it have?