Learn JavaScript · lesson 51 of 60 · about 8 minutes
Tracing and Fixing Recursion
Follow every call step by step, and spot recursion that never stops.
What you'll learn
- Trace the order of recursive calls
- Explain what the call stack is
- Fix a missing or unreachable base case
The 3n + 1 game
Sam's page gets a number game for visitors. Take their number: if it's even, halve it; if it's odd, times it by 3 and add 1; keep going until you reach 1. 6 goes 3, 10, 5, 16, 8, 4, 2, 1, so the page says 6 reaches 1 in 8 steps. stepsToOne(1) is 0, and any other number takes 1 more step than the number after it, added up on the way back out of the calls. But some numbers never reach 1 at all: 0 halves to 0 forever, and negative numbers and fractions never get there either, so the page checks the number before it starts.
The call stack
When a function calls itself, the first call waits while the new one runs. JavaScript keeps all the waiting calls on the call stack, like a pile of plates.
When the base case returns, the calls finish one by one, newest first. Code after the recursive call runs on the way back out.
In and out
function dive(n) {
if (n === 0) {
console.log("bottom");
return;
}
console.log("going down", n);
dive(n - 1);
console.log("coming up", n);
}
dive(2);Output
going down 2
going down 1
bottom
coming up 1
coming up 2When it never stops
If the base case is missing, or the calls never reach it, the stack keeps growing until JavaScript gives up with RangeError: Maximum call stack size exceeded. Check that every path makes the problem smaller and that the base case catches the smallest one.
Catching a runaway
function forever(n) {
return forever(n + 1);
}
try {
forever(1);
} catch (e) {
console.log(e.name);
}Output
RangeErrorCheck before you start
Sometimes the base case is right, but some inputs can never reach it. Halving 64 reaches 1, but halving 0 never does. When the input comes from a visitor, check it first and show a message, so the recursion only ever starts on numbers that will finish.
Only start on numbers that finish
function halvings(n) {
if (n === 1) return 0;
return 1 + halvings(n / 2);
}
const box = document.querySelector("#halves");
const n = 64;
box.textContent = n >= 1 ? `${n} halves down to 1 in ${halvings(n)} steps` : "Pick a number from 1 up";
console.log(box.textContent);Output
64 halves down to 1 in 6 stepsTip
To trace a recursive call by hand, write each call on its own line, indented one step further than the call that made it.
Now try it yourself
This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.