Tail recursion
Intermediate · 8 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Tail recursion is a way of writing a recursive function so that the self-call is the very last thing it does, carrying the running answer along. Then no pending work piles up, and the call can be turned into a plain loop with no memory growth.
Practical use cases
- Web app: Summing a huge list of invoices. A JavaScript dashboard adds up 100,000 invoice amounts with a normal recursive function and the browser throws a stack overflow error. Rewriting it so the running total is passed along, or just using a loop, removes the pile of waiting calls. The total now appears without any crash.
- Web app: Processing a queue of jobs. A Node.js worker handles one job and then calls itself to take the next. If each call keeps the previous one waiting, memory slowly grows until the worker dies after a few hours. Handing off to the next job as the final act, or using a loop, lets it run all week.
- System: Functional language compilers. Languages like Scheme and Haskell promise to turn last-position self-calls into jumps, so loops are written as recursion with no cost. Developers who understand the pattern can convert any deep recursion into a loop when their language does not do it for them.
The story: The Relay Baton
On Sports Day, Mira's school ran a relay race. Mrs. Sharma noticed something. "Look, when the runner hands over the baton, her job is completely done. She does not have to wait at the track, she can sit down."
Then she pointed at the quiz round. "In this game, I ask Zoya a question, and Zoya must ask Aarav, but when Aarav answers, Zoya still has to add her own 5 marks before replying to me. So Zoya must stand and wait. And so does everyone in the chain." The line of waiting students grew longer and longer.
Kabir had an idea. "What if Zoya added her 5 marks first and handed the running total to Aarav, like a baton? Then when Aarav has the final answer, he can call it out directly, and nobody needs to wait!"
That is tail recursion: the recursive call is the very last thing the function does, and the partial answer rides along in an extra parameter (the accumulator). Some languages notice that nobody is waiting and reuse one frame, so deep recursion costs no extra stack.
How to spot this problem, and where you need it
A recursive function works on small inputs but fails with a stack overflow or memory error when the list, count or depth gets large, even though the logic is correct.
Signs you need it
- The error appears only with big inputs, such as 10,000 or more levels of recursion, and not with test data.
- After each recursive call returns, the function still has to do something, like add a number or join a string.
- A long-running job slowly eats memory while repeating itself through self-calls.
Where to use it in a project
- Replacing a recursive total, counter or list walker with a loop when the data can be very long.
- Writing background workers, retry handlers and polling loops that must run for days without growing memory.
The solution
Add an extra parameter, often called an accumulator, that holds the answer so far. Instead of waiting for the call to return and then adding, do the adding first and pass the result into the next call, so that the call is the last thing the function does. Then change it into a loop: update the variables and repeat. Memory stays flat no matter how long the list.
Payoff: Before: summing 100,000 values crashes with stack overflow. After: the loop version handles a million values using almost no extra memory.
Explain it like I am 8
Imagine passing a note down a line of kids. In the slow way every kid writes "plus my number" on their own paper and keeps it until the answer comes back. In the fast way each kid updates the one note and passes it on, so nobody has to keep anything.
How it works, step by step
- Spot the waiting work: in
n * fact(n-1)the multiply happens after the call returns, so each call must wait. - Add an accumulator parameter that holds the answer so far, like
acc = 1. - Do the work before the call:
return fact(n-1, acc * n). - The base case returns the accumulator:
if (n <= 1) return acc;. - Be honest about your language: Scheme and some others reuse the frame; PHP and most JavaScript engines do not, so there you can write the same idea as a plain loop.
The code in four languages
PHP
<?php
// 1. Normal recursion: the multiply waits until the inner call returns.
function factNormal(int $n): int {
if ($n <= 1) return 1;
return $n * factNormal($n - 1); // work AFTER the call
}
// 2. Tail recursion: running answer rides in $acc, call is the last step.
function factTail(int $n, int $acc = 1): int {
if ($n <= 1) return $acc;
return factTail($n - 1, $acc * $n); // nothing left to do afterwards
}
// 3. What tail-call optimisation effectively does: reuse ONE frame (a loop).
function factLoop(int $n): int {
$acc = 1;
while ($n > 1) {
$acc *= $n;
$n--;
}
return $acc;
}
echo factNormal(5) . "
"; // 120
echo factTail(5) . "
"; // 120
echo factLoop(5) . "
"; // 120JavaScript
// 1. Normal recursion: the multiply waits until the inner call returns.
function factNormal(n) {
if (n <= 1) return 1;
return n * factNormal(n - 1); // work AFTER the call
}
// 2. Tail recursion: running answer rides in acc, call is the last step.
function factTail(n, acc = 1) {
if (n <= 1) return acc;
return factTail(n - 1, acc * n); // nothing left to do afterwards
}
// 3. What tail-call optimisation effectively does: reuse ONE frame (a loop).
function factLoop(n) {
let acc = 1;
while (n > 1) {
acc *= n;
n--;
}
return acc;
}
console.log(factNormal(5)); // 120
console.log(factTail(5)); // 120
console.log(factLoop(5)); // 120Java
public class Main {
// 1. Normal recursion: the multiply waits until the inner call returns.
static int factNormal(int n) {
if (n <= 1) return 1;
return n * factNormal(n - 1); // work AFTER the call
}
// 2. Tail recursion: running answer rides in acc, call is the last step.
static int factTail(int n, int acc) {
if (n <= 1) return acc;
return factTail(n - 1, acc * n); // nothing left to do afterwards
}
// 3. What tail-call optimisation effectively does: reuse ONE frame (a loop).
static int factLoop(int n) {
int acc = 1;
while (n > 1) {
acc *= n;
n--;
}
return acc;
}
public static void main(String[] args) {
System.out.println(factNormal(5)); // 120
System.out.println(factTail(5, 1)); // 120
System.out.println(factLoop(5)); // 120
}
}Go
package main
import "fmt"
// 1. Normal recursion: the multiply waits until the inner call returns.
func factNormal(n int) int {
if n <= 1 {
return 1
}
return n * factNormal(n-1) // work AFTER the call
}
// 2. Tail recursion: running answer rides in acc, call is the last step.
func factTail(n, acc int) int {
if n <= 1 {
return acc
}
return factTail(n-1, acc*n) // nothing left to do afterwards
}
// 3. What tail-call optimisation effectively does: reuse ONE frame (a loop).
func factLoop(n int) int {
acc := 1
for n > 1 {
acc *= n
n--
}
return acc
}
func main() {
fmt.Println(factNormal(5)) // 120
fmt.Println(factTail(5, 1)) // 120
fmt.Println(factLoop(5)) // 120
}Time: O(n) · Extra space: O(1) with tail-call optimisation, otherwise O(n). Time is the same as normal recursion; the gain is stack space, but only in languages that really optimise tail calls.
Watch out for
- Thinking
return n * f(n-1)is tail recursion. The multiply happens after the call, so it is not. - Assuming PHP or Node will optimise tail calls for you. They generally do not, so deep recursion can still overflow.
- Forgetting to give the accumulator a sensible starting value, such as 1 for products and 0 for sums.
Quick check
- Which call is a tail call?
- return 1 + f(n-1)
- return f(n-1, acc + n)
- return f(n-1) * 2
- What is the accumulator for?
- Holding the answer built so far, passed along the calls
- Counting stack overflow
- Sorting
- In PHP, does writing tail-recursive code avoid stack overflow?
- Yes, always
- No, PHP does not do tail-call optimisation
- Only for strings