Skip to main content
πŸ” Recursion

Fibonacci

Now write the recursion you just studied. Two base cases, two recursive calls:

function fib(n) {
  if (n < 2) return n;             // base cases: fib(0)=0, fib(1)=1
  return fib(n - 1) + fib(n - 2);  // sum of the two previous
}
fib(7); // 13

Your task

Write fib(n) that returns the nth Fibonacci number (0-indexed, so fib(0) === 0 and fib(1) === 1).

⚑ 45 XP

🧱 Code blocks

Drag a block into the editor, or tap it to drop it in where your cursor is. Add them in order to build your answer.

solution.jsRuns in your browser
Loading editor…
Tests5 to pass
fib(0) β†’ 0
fib(1) β†’ 1
fib(7) β†’ 13
fib(10) β†’ 55
fib(15) β†’ 610

Run your code to check these.