Skip to content
Algorithms for Beginners

Learn / Lesson 9 of 10

Recursion

Solve a problem by solving a smaller copy of the same problem.

Words on this page, in plain English (12)Open if any word is new to you
Variable
A labelled box that holds a value. You give it a name, put something in it, and use the name later to get it back.
Array (list)
A list of values kept in order, inside square brackets. Like a row of numbered lockers.
Length
How many items a list (or letters a string) has. The last position is always length - 1.
If (a decision)
Runs some code only when something is true. Like: if it's raining, take an umbrella.
Loop
Code that repeats. A for loop repeats once per item or a set number of times; a while loop repeats as long as something stays true.
Function
A named, reusable recipe. You give it ingredients (inputs), it does its steps, and hands back a result.
Return
How a function hands back its answer. As soon as return runs, the function stops.
console.log
Prints something so you can see it. The easiest way to find out what your code is really doing.
Pattern
A trick that solves a whole family of problems. Learn the trick once, and you can solve problems you've never seen.
Sorted
In order, smallest to biggest (or A to Z). Many fast tricks only work on sorted lists.
Stack
A pile where you only touch the top: add with push, take with pop. The last thing in is the first out, like a pile of plates.
Recursion
A function that calls itself on a smaller version of the problem, until the problem is small enough to answer directly.

Every word, explained simply

A function that calls itself

Recursion means a function solving a problem by calling itself on a smaller version of the same problem. It sounds like a trick, but it's a natural way to describe many things.

Think of a countdown from 5. You could say: "say 5, then do a countdown from 4". A countdown from 4 is "say 4, then do a countdown from 3"... until "a countdown from 0 is: say liftoff".

Try it: a countdown

function countdown(n) {
if (n === 0) {
  console.log("Liftoff!");
  return;
}
console.log(n);
countdown(n - 1);   // the same problem, one smaller
}
countdown(5);

Press Run to see the output. You can change the code first.

The two parts

Every recursive function has:

  1. A base case: a version so small you can answer it directly, without recursion. (n === 0: say liftoff.)
  2. A recursive case: answer using the answer to a smaller version. (Say n, then count down from n - 1.)

Each call must get closer to the base case, or it never ends.

Building a result

Recursive functions usually return something built from the smaller answer. The sum of a list is "the first item, plus the sum of the rest":

Try it: sum of a list

function sum(nums) {
if (nums.length === 0) return 0;        // base case: nothing to add
return nums[0] + sum(nums.slice(1));    // first + sum of the rest
}
console.log(sum([4, 1, 7, 3]));

Press Run to see the output. You can change the code first.

Trace it by hand: sum([4, 1, 7, 3]) is 4 + sum([1, 7, 3]), which is 4 + 1 + sum([7, 3])… down to 4 + 1 + 7 + 3 + sum([]), which is + 0. Then all the waiting additions finish: 15.

The call stack

How does the computer keep track of all those waiting calls? It keeps a stack of them, like the Stack pattern: each call waits on top of the one that called it, and when the base case returns, they finish one by one from the top.

Try it: watching the calls

function factorial(n, depth = 0) {
const indent = "  ".repeat(depth);
console.log(indent + "factorial(" + n + ") starts");
const result = n <= 1 ? 1 : n * factorial(n - 1, depth + 1);
console.log(indent + "factorial(" + n + ") returns " + result);
return result;
}
factorial(4);

Press Run to see the output. You can change the code first.

(The factorial of 4 is 4 × 3 × 2 × 1 = 24.)

When the base case is missing

Without a base case, the function calls itself forever, the stack of waiting calls grows until there's no room, and JavaScript stops it with a "Maximum call stack size exceeded" error:

Try it: no base case

function forever(n) {
return forever(n - 1);
}
forever(10);

Press Run to see the output. You can change the code first.

When to use recursion

Recursion shines when a problem is made of smaller copies of itself:

  • Trees: a folder contains folders; a family tree contains smaller family trees.
  • Trying every option: choose the first item or not, then solve the rest the same way (backtracking).
  • Divide and conquer: split in half, solve each half, combine (merge sort, binary search).

For a simple list, a loop is usually clearer and avoids running out of stack. Recursion is a tool, not a rule.

Your turn

Write power(base, exp) that works out base to the power exp (like 2⁵ = 32) with recursion. Base case: anything to the power 0 is 1.

Your turn

function power(base, exp) {
}

console.log(power(2, 5));
console.log(power(3, 0));

Press Run to see the output. You can change the code first.

What you learned

  • A recursive function calls itself on a smaller problem.
  • It needs a base case that stops the recursion.
  • Waiting calls are kept on the call stack.
  • Recursion fits problems made of smaller copies of themselves: trees, choices, divide and conquer.