JSVisualizer is a free browser-based tool that runs JavaScript step by step and shows you what's happening in 12 different views. There's nothing to install. This is part of a series that uses it to understand classic algorithms by watching them run, but this post stands on its own. For an overview of the tool, see the first post in the series.
This time the topic is recursion, and the star of the show is the Subst view.
Where beginners get stuck
A function that calls itself is called recursive. This one computes x to the power of n (x multiplied together n times). Here we assume n is a whole number, 0 or greater:
function power(x, n) { if (n === 0) { return 1; } return x * power(x, n - 1); } console.log(power(2, 5)); You don't need to copy the code. This link opens it ready to run:
▶ Open in JSVisualizer (power, Subst view)
The idea goes like this:
- Anything to the power of 0 is 1.
-
xto the power ofnisxtimes (xto the power ofn - 1).
So 2 to the power of 5 is 32. But when you're new to recursion, it's easy to get stuck on questions like these:
- The function uses itself before it's even finished being defined. Why does that work?
- Where does the multiplication happen? How can
x * power(x, n - 1)multiply anything whenpower(...)doesn't have an answer yet? - When does it stop?
Try following it in your head and you'll soon be lost in calls within calls within calls. JSVisualizer's Subst view takes a different angle, one that looks a lot like rewriting an equation in math class: it replaces each function call with the expression that function returns.
Seeing it in the Subst view
How to read it
Open the link above and press ▶ Run; the Subst view opens. (If you pasted the code into JSVisualizer yourself, press ▶ Run and open the Subst tab.) Press the End key to jump to the end:
Read it from top to bottom:
- The top row is the first call,
power(2, 5). - Each row after that replaces a function call with the expression from that function's
return. The orange part is what was just replaced. -
Line 5tells you which line'sreturndid the replacing. Line 5 of the code isreturn x * power(x, n - 1);, and line 3 isreturn 1;. - The blue row is your current position. Press ▷ Human (one "human-friendly" step) to move down.
Reading row by row
Row 2 rewrites power(2, 5) as 2 * power(2, 4). With x as 2 and n as 5, that's return x * power(x, n - 1); with 2 for x and 4 for n - 1.
Row 3 applies the same rule to the remaining power(2, 4), turning it into 2 * power(2, 3). The expression is now 2 * 2 * power(2, 3).
The same small job repeats: rewrite the one function call that's left. "Calling itself" sounds mysterious, but in the Subst view all you see is the same problem being replaced by a slightly smaller version of itself, using the same rule.
JavaScript doesn't actually rewrite your code as it runs, though. What really happens is that each call creates a new frame (a box just for that call, which you can see in the Call Stack view from an earlier post). The Subst view presents that calculation as if it were an equation being rewritten in math class.
What the expansion reveals
1. Recursion rewrites a problem as a slightly smaller one
power(2, 5) → power(2, 4) → power(2, 3): the second argument shrinks by 1 each time.
So what about the question from the start, about a function using itself before it's finished being defined? Defining a function doesn't run the code inside it. By the time you actually call power(2, 5), the function power already exists and is ready to use, so the code inside it can call power too.
You do need something to keep it from calling itself forever, though. Recursion finds an answer because it's built so that every call makes the problem smaller, until it eventually reaches a form whose answer is known directly.
2. The base case stops the rewriting
At power(2, 0), n === 0 is true and return 1; runs. The second-to-last row is labeled Line 3, and for the first time the expression has no function calls left: 2 * 2 * 2 * 2 * 2 * 1.
A case where the function returns the answer directly, without recursing, is called the base case. The stopping condition that decides when to take it is n === 0 here. Every recursive function has two parts: the base case, and the part that replaces the problem with a smaller version of the same problem.
3. The multiplying waits until the bottom
While the rewriting goes on, 2 *s pile up on the left, and not a single multiplication has happened yet. 2 * ... can't be worked out until the answer to power(2, 4) is known.
Only when the innermost power(2, 0) returns 1 can the multiplying begin. The real calculation works back outward (2 * 1, 2 * 2, 2 * 4, ...), though the Subst view sums all of that up in the final 32.
Also note that the Subst view writes the multiplications side by side as 2 * 2 * 2 * 2 * 2 * 1, but they actually group as 2 * (2 * (2 * (2 * (2 * 1)))). Where dropping the parentheses makes no mathematical difference, as with a chain of * or a chain of +, the Subst view leaves them out; for other combinations it keeps them.
Recursion like power, where there's still work to do with the returned value, has two phases: calling down while the problem shrinks, and then using the answers that come back to build the answer to the original problem.
4. Forget the base case and it never stops
What happens if we delete the if?
function power(x, n) { return x * power(x, n - 1); } console.log(power(2, 5)); The rewriting never ends. The expression keeps growing and function calls pile up until the program stops with an error, while n sails past 0 to -1, -2, and beyond.
Having a stopping condition isn't enough on its own, either. Keep the if but call power(2, -1), and n moves away from 0 (-2, -3, ...), so it never stops. When you write a recursive function, check two things: where it stops (the stopping condition), and whether every call gets closer to it.
That's it for the basics of recursion. Next, let's look at some recursion with a different shape.
5. Not all recursion makes the expression longer
This function finds the greatest common divisor of two numbers (the largest whole number that divides both of them evenly):
function gcd(a, b) { if (b === 0) { return a; } return gcd(b, a % b); } console.log(gcd(48, 18)); a % b is the remainder when a is divided by b. This is the Euclidean algorithm, which relies on the fact that the greatest common divisor of two whole numbers a and b equals the greatest common divisor of b and a % b (we'll stick to positive whole numbers here).
This time there's no 2 * waiting to be calculated, so the expression doesn't grow. The return is nothing but a function call, so one problem simply turns into another. Both functions are recursive, but the difference in shape is obvious at a glance.
6. Halve the problem and the calls drop sharply
Our first power shrinks n by 1 each time. But when n is even, we can do much better: 2 to the 10th is the square of 2 to the 5th.
function square(y) { return y * y; } function fastPower(x, n) { if (n === 0) { return 1; } if (n % 2 === 0) { return square(fastPower(x, n / 2)); } return x * fastPower(x, n - 1); } console.log(fastPower(2, 10)); If n is even, halve it and square the result. If it's odd, subtract 1 just as power does. (Again, n is a whole number, 0 or greater.) This technique is called exponentiation by squaring.
There are two things to look for here:
- How fast
nshrinks: it goes 10 → 5 → 4 → 2 → 1 → 0, sofastPoweris called just 6 times, compared with 11 forpower(2, 10). The gap widens quickly: withnat 1000,powermakes 1001 calls andfastPowermakes 16. (These counts are calls topowerandfastPowerthemselves; calls tosquarearen't included.) An oddnonly drops by 1, but subtracting 1 from an odd number gives an even number, sonis always at least halved within two calls. - How
squarewaits: thesquareinsquare(fastPower(2, 5))can't run until its argument has a value, so the innerfastPowerexpands first. Only whensquare(2 * 1)has becomesquare(2)does execution entersquare, turning it into2 * 2. The values you pass to a function are worked out before the function starts, and here you can watch that order play out.
In an earlier post on nested loops, we judged an algorithm's efficiency by counting how often its loops ran. You can do the same with recursion by counting calls. The number of calls to power grows in proportion to n (O(n)). fastPower keeps halving the problem, so its call count grows far more slowly (O(log n); log n is roughly how many times you can halve n before reaching 1).
Try it yourself
Open the link below and press ▶ Run; the Subst view opens. Step forward with ▷ Human (the h key) and back with ◁ Human (H).
▶ Open in JSVisualizer (power, Subst view)
To change the code, press ✏ Edit. Before each run, predict the expressions you'll see:
- Change
power(2, 5)topower(3, 4). How many rows will there be? What's the last expression? - Change
power(2, 5)topower(2, 0). How many replacements happen? - Change
power(2, 5)topower(2, -1). There's a stopping condition, so why doesn't it stop? - Switch to the Call Stack tab and step with ▷ Human. When are there the most frames, and which row of the Subst view does that moment match?
More programs to play with:
- ▶ Power with no base case: this one opens in the Call Stack view. Press ▷ Human and watch the calls pile up, or press
Endto see all the calls at the point where it stopped. - ▶ Greatest common divisor: change
gcd(48, 18)togcd(18, 48). What does the first replacement do? - ▶ Power by halving: switch to the Call Tree tab. How are the
fastPowercalls arranged?
Wrapping up
- The Subst view replaces each function call with the expression in its
return, showing the calculation from top to bottom like an equation being rewritten. - Recursion combines replacing a problem with a slightly smaller version of itself and a base case where the answer is returned directly. You need a stopping condition, and every call has to get closer to it.
- When work with the returned value is left waiting, as in
x * power(...), the expression grows. When the returned value is passed straight back, as ingcd(...), it doesn't. - Recursion that keeps halving the problem, like
fastPower, makes far fewer calls than recursion that shrinks it by 1 (O(log n) versus O(n)).
Next up: sorting. We'll watch array elements swap places in the Arrays view.



