Skip to content
Devtoolry

Numbers · beginner

JavaScript Program to Print the Fibonacci Sequence

Print the Fibonacci sequence in JavaScript with a loop and destructuring, see why naive recursion is slow, and fix it with memoization in a Map.

In the Fibonacci sequence each number is the sum of the two before it: 0, 1, 1, 2, 3, 5, 8, 13, … It is the standard example for comparing loops with recursion, because the obvious recursive version repeats the same work an enormous number of times.

The program

JavaScript
const n = 10;
let [a, b] = [0, 1];
const terms = [];

for (let i = 0; i < n; i++) {
  terms.push(a);
  [a, b] = [b, a + b];
}

console.log(`First ${n} Fibonacci numbers:`);
console.log(terms.join(", "));
Output
First 10 Fibonacci numbers:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34

How it works

  1. a and b hold two consecutive Fibonacci numbers, starting with 0 and 1.
  2. Each pass pushes a, then moves both forward: [a, b] = [b, a + b] builds the new pair from the old values before assigning.
  3. After n passes, terms holds the first n numbers.
  4. join(", ") turns the array into one line of text.

Watch it run line by line

Watch a and b move forward together on the destructuring line while terms grows by one element per pass.

“Visualize step by step” opens the program in the JavaScript Compiler and records every step in your browser. Use the arrow keys to move forwards and backwards; changed variables are highlighted.

Another way: Recursion with memoization

fib(n) = fib(n - 1) + fib(n - 2) recalculates the same values over and over: fib(30) alone makes over 1.6 million calls. Remembering results in a Map makes every value cost one call.

JavaScript
const memo = new Map();
function fib(n) {
  if (n < 2) return n;
  if (memo.has(n)) return memo.get(n);
  const value = fib(n - 1) + fib(n - 2);
  memo.set(n, value);
  return value;
}

console.log(Array.from({ length: 10 }, (_, i) => fib(i)).join(", "));
console.log(fib(78));
Output
0, 1, 1, 2, 3, 5, 8, 13, 21, 34
8944394323791464

Common mistakes

  • Updating a and b in two statements (a = b; b = a + b;): the second line then uses the new a.
  • Using plain recursion for large n: fib(40) without memoization takes seconds.
  • Going past fib(78): from fib(79) the values exceed Number.MAX_SAFE_INTEGER and lose precision. Use BigInt.

Try it yourself

  • Print all Fibonacci numbers below 1,000 with a while loop.
  • Write a generator function* that yields Fibonacci numbers forever and take the first 15.

Open the program in the JavaScript Compiler, change it and press Run: there is nothing to install, and your code never leaves your browser.

Browse all 25 JavaScript examples, or write your own program in the online JavaScript Compiler.