Emmanuel Akinfulubi

JavaScriptRecursion

Fibonacci using recursion in JavaScript

Intermediate · 3 min read

The Fibonacci sequence starts 0, 1, and then every number is the sum of the two before it: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34. It turns up in nature (the spirals of a sunflower), in art, and in almost every course that teaches recursion, because its definition is already recursive.

In this tutorial you will write fib(n) straight from that definition, measure how wasteful it is, and then fix it with memoization, a trick that makes it hundreds of times faster. Finally you will return the first n numbers as a list. You need to know functions, arrays and if. Recursion is explained from zero.

The definition is the code

Number the positions from 0. Then:

Worked example

fib(0) = 0
fib(1) = 1
fib(n) = fib(n - 1) + fib(n - 2)   for every n of 2 or more

A recursive function calls itself on smaller inputs. The first two lines are the base cases, where it answers straight away. The last line is the recursive case. This one has two base cases because each number needs the two before it.

Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.

6 The first n Fibonacci numbers

fair

Return the first n numbers of the sequence 0, 1, 1, 2, 3, 5, 8, 13… Then measure how badly the obvious recursion behaves.

Stuck? Three hints, smallest first
  1. 1. Two base cases: fib(0) is 0 and fib(1) is 1.
  2. 2. Calling fib once per position recomputes the same values over and over.
  3. 3. A Map of already-computed answers turns exponential time into linear.

Step 1: translate the definition

Positions 0 and 1 answer themselves, so n < 2 can return n directly:

Step 1

function fib(n) {
  return n < 2 ? n : fib(n - 1) + fib(n - 2);
}
console.log(fib(0));  // 0
console.log(fib(1));  // 1
console.log(fib(10)); // 55
console.log(fib(25)); // 75025

It works, and it is one line. Now look at what it does.

Step 2: see the repeated work

Write out the calls for fib(5):

Worked example

fib(5)
├─ fib(4)
│  ├─ fib(3)
│  │  ├─ fib(2) ...
│  │  └─ fib(1)
│  └─ fib(2) ...
└─ fib(3)
   ├─ fib(2) ...
   └─ fib(1)

fib(3) is worked out twice and fib(2) three times. Every level doubles the waste. Count it for fib(25):

Step 2

let plain = 0;
const countPlain = (n) => { plain++; return n < 2 ? n : countPlain(n - 1) + countPlain(n - 2); };
countPlain(25);
console.log(plain); // 242785

Nearly a quarter of a million calls to find the 25th number. Each extra position multiplies the count by about 1.6, so fib(40) makes over 300 million calls.

Step 3: remember the answers

Memoization means storing each answer the first time you work it out, and looking it up after that. A Map is a good store: set(key, value) saves, has(key) checks and get(key) reads.

Step 3

function fibMemo(n, seen = new Map()) {
  if (n < 2) return n;
  if (seen.has(n)) return seen.get(n);
  const value = fibMemo(n - 1, seen) + fibMemo(n - 2, seen);
  seen.set(n, value);
  return value;
}
console.log(fibMemo(25)); // 75025

seen = new Map() is a default parameter: the first call creates an empty map, and every recursive call passes the same map along. So every call shares one memory.

Step 4: count again

Step 4

let memo = 0;
const countMemo = (n, seen = new Map()) => {
  memo++;
  if (n < 2) return n;
  if (seen.has(n)) return seen.get(n);
  const v = countMemo(n - 1, seen) + countMemo(n - 2, seen);
  seen.set(n, v);
  return v;
};
countMemo(25);
console.log(memo); // 49

From 242,785 calls down to 49, with three extra lines. Each position is now worked out once; the other calls are instant lookups.

Step 5: the first n numbers

The task wants a list. Array.from({ length: n }, (_, i) => ...) builds an array of n items, working out each one from its position i:

Step 5

function fibMemo(n, seen = new Map()) {
  if (n < 2) return n;
  if (seen.has(n)) return seen.get(n);
  const value = fibMemo(n - 1, seen) + fibMemo(n - 2, seen);
  seen.set(n, value);
  return value;
}
const firstN = (n) => Array.from({ length: n }, (_, i) => fibMemo(i));
console.log(firstN(10)); // [ 0, 1, 1, 2, 3, 5, 8, 13, 21, 34 ]
console.log(firstN(1));  // [ 0 ]
console.log(firstN(0));  // []

Step 6: watch for big numbers

Fibonacci numbers grow quickly. Number.isSafeInteger tells you whether a whole number is still stored exactly:

JavaScript

function fibMemo(n, seen = new Map()) {
  if (n < 2) return n;
  if (seen.has(n)) return seen.get(n);
  const value = fibMemo(n - 1, seen) + fibMemo(n - 2, seen);
  seen.set(n, value);
  return value;
}
console.log(Number.isSafeInteger(fibMemo(78))); // true
console.log(Number.isSafeInteger(fibMemo(90))); // false

Past the safe range, the last digits can't be trusted. For huge positions, use BigInt.

The full solution

The panel has the plain and memoized versions, firstN, and counters that check the exact number of calls each one makes. Press Run to see the output.

The answer

// The textbook definition. Also the textbook example of accidental waste:
// fib(n - 1) and fib(n - 2) recompute overlapping work.
function fib(n) {
  return n < 2 ? n : fib(n - 1) + fib(n - 2);
}

// Remember what you already worked out.
function fibMemo(n, seen = new Map()) {
  if (n < 2) return n;
  if (seen.has(n)) return seen.get(n);
  const value = fibMemo(n - 1, seen) + fibMemo(n - 2, seen);
  seen.set(n, value);
  return value;
}

const firstN = (n) => Array.from({ length: n }, (_, i) => fibMemo(i));

// Count the calls each way.
let plain = 0;
let memo = 0;
const countPlain = (n) => { plain++; return n < 2 ? n : countPlain(n - 1) + countPlain(n - 2); };
const countMemo = (n, seen = new Map()) => {
  memo++;
  if (n < 2) return n;
  if (seen.has(n)) return seen.get(n);
  const v = countMemo(n - 1, seen) + countMemo(n - 2, seen);
  seen.set(n, v);
  return v;
};
countPlain(25);
countMemo(25);

console.log('first 10   :', firstN(10));
console.log('fib(25)    :', fib(25));
console.log('calls for fib(25) — plain:', plain, ' memoised:', memo);
console.log('fib(90)    :', fibMemo(90), '<- already past safe integers');

Output


      
12 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 12 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

12 checks

test('the first ten', firstN(10), [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]);
test('the first one is just [0]', firstN(1), [0]);
test('asking for none gives an empty list', firstN(0), []);
test('fib(0) is 0', fib(0), 0);
test('fib(1) is 1', fib(1), 1);
test('fib(10) is 55', fib(10), 55);
test('memoised agrees for 0 to 25', Array.from({ length: 26 }, (_, i) => fib(i) === fibMemo(i)).every(Boolean), true);
test('each number is the sum of the two before it', firstN(20).slice(2).every((v, i) => v === firstN(20)[i] + firstN(20)[i + 1]), true);
test('the plain version makes 242785 calls for n=25', plain, 242785);
test('which is exactly 2*fib(26) - 1', plain, 2 * fibMemo(26) - 1);
test('memoised needs 49', memo, 49);
test('fib(90) is past safe integers, so treat it with suspicion', Number.isSafeInteger(fibMemo(90)), false);

The call count is not approximately exponential, it is exactly 2 × fib(n+1) − 1, and the assertion checks that identity rather than describing it. For n = 25 that is 242,785 calls to produce a number you could reach in 25 steps; at n = 40 it is over 300 million. Memoising is a one-line change and the assertion shows it drops to 49 calls. This is the cheapest possible demonstration of why "it terminates" and "it is usable" are different claims.

Common mistakes

  • Using only one base case. With just n === 0, fib(1) calls fib(-1) and never stops. You need both 0 and 1.
  • Creating a new Map on every call. If each recursive call made its own new Map(), nothing would be shared. Pass seen down.
  • Shipping the plain version. It answers small inputs fine, but by fib(40) it is making hundreds of millions of calls.

Try it yourself

  1. Write fibLoop(n) with a loop and two variables, and check it agrees with fibMemo for 0 to 30.
  2. Find the first position whose Fibonacci number has more than 10 digits.
  3. Rewrite fibMemo with BigInt (start from 0n and 1n) and print fib(100) exactly.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.