A recursive function is a function that calls itself. That sounds like a loop that never ends, but each call works on a smaller piece of the problem until the piece is so small that the answer is obvious. Recursion is the natural way to handle nested data such as folder trees, menus, comments with replies and JSON documents. This lesson shows how it works, how to write it safely and when a loop is the better choice.
In this lesson you will learn
- The base case and the recursive case
- How the call stack keeps track of each call
- Walking nested data such as folder trees
- Why some recursion is slow, and how memoisation fixes it
- Stack overflow errors and when to use a loop instead
You should know functions, arrays and objects.
Base Case and Recursive Case
// Factorial: the classic recursive function
function factorial(n) {
if (n <= 1) return 1; // base case: stops the recursion
return n * factorial(n - 1); // recursive case: a smaller problem
}
console.log("5! =", factorial(5));
// Sum the digits of a number
function digitSum(n) {
if (n < 10) return n;
return (n % 10) + digitSum(Math.floor(n / 10));
}
console.log("digitSum(2026) =", digitSum(2026));
// Watch the calls go down and come back up
function countdown(n, depth = 0) {
const pad = " ".repeat(depth);
if (n === 0) { console.log(pad + "reached 0, returning"); return; }
console.log(pad + "countdown(" + n + ")");
countdown(n - 1, depth + 1);
console.log(pad + "back in countdown(" + n + ")");
}
countdown(3);
// Without a base case, the call stack overflows
function forever(n) { return forever(n + 1); }
try {
forever(0);
} catch (err) {
console.log(err.name + ":", err.message);
}
Output
5! = 120
digitSum(2026) = 10
countdown(3)
countdown(2)
countdown(1)
reached 0, returning
back in countdown(1)
back in countdown(2)
back in countdown(3)
RangeError: Maximum call stack size exceeded
- Every recursive function needs two parts. The base case is a simple input with a known answer, like
factorial(1)is 1. The recursive case calls the function again with a smaller input. factorial(5)becomes5 * factorial(4), then5 * 4 * factorial(3), and so on until it reaches the base case.digitSumremoves one digit per call: 2026 becomes 202, then 20, then 2.- The
countdownoutput shows the two halves of recursion. Calls go down until the base case, then each waiting call finishes on the way back up. - Without a base case, the calls never stop. JavaScript throws
RangeError: Maximum call stack size exceededinstead of running forever.
Recursion on Nested Data
// Recursion shines on nested data: a folder tree
const folder = {
name: "Documents",
files: ["cv.pdf", "notes.txt"],
folders: [
{ name: "Photos", files: ["sylhet.jpg", "coxs-bazar.jpg", "dhaka.jpg"], folders: [] },
{ name: "School", files: ["math.docx"], folders: [
{ name: "Physics", files: ["lab1.pdf", "lab2.pdf"], folders: [] }
] }
]
};
function countFiles(dir) {
let total = dir.files.length;
for (const sub of dir.folders) total += countFiles(sub); // same job, smaller folder
return total;
}
console.log("Total files:", countFiles(folder));
function printTree(dir, indent = "") {
console.log(indent + dir.name + "/");
for (const sub of dir.folders) printTree(sub, indent + " ");
for (const f of dir.files) console.log(indent + " " + f);
}
printTree(folder);
// Flatten nested arrays of any depth
function flatten(arr) {
const out = [];
for (const item of arr) {
if (Array.isArray(item)) out.push(...flatten(item));
else out.push(item);
}
return out;
}
console.log(flatten([1, [2, [3, [4, 5]]], 6]));
// Fibonacci: plain recursion repeats work, a memo remembers answers
let calls = 0;
function fibSlow(n) { calls++; return n < 2 ? n : fibSlow(n - 1) + fibSlow(n - 2); }
fibSlow(25);
console.log("fibSlow(25) made", calls, "calls");
const memo = new Map();
let calls2 = 0;
function fibFast(n) {
calls2++;
if (n < 2) return n;
if (memo.has(n)) return memo.get(n);
const value = fibFast(n - 1) + fibFast(n - 2);
memo.set(n, value);
return value;
}
console.log("fibFast(25) =", fibFast(25), "using", calls2, "calls");
Output
Total files: 8
Documents/
Photos/
sylhet.jpg
coxs-bazar.jpg
dhaka.jpg
School/
Physics/
lab1.pdf
lab2.pdf
math.docx
cv.pdf
notes.txt
[ 1, 2, 3, 4, 5, 6 ]
fibSlow(25) made 242785 calls
fibFast(25) = 75025 using 49 calls
- A folder can contain folders, which can contain more folders. You cannot know in advance how deep it goes, so a fixed number of loops will not work.
countFilescounts the files in one folder, then asks itself to count each sub-folder. An emptyfoldersarray is the base case: the loop simply does not run.printTreepasses a longerindentto each deeper call, so the output shows the tree shape.flattenunpacks arrays inside arrays at any depth. (The built-inarr.flat(Infinity)does the same job.)fibSlowcalls itself twice per step, so it recalculates the same values again and again: 242,785 calls forfib(25).fibFaststores each answer in aMapthe first time. This is called memoisation. Later requests for the same value are answered at once, and only 49 calls are needed.
| Use recursion for | Prefer a loop for |
|---|---|
| Trees: folders, menus, the DOM, comment replies | Simple counting and repeating |
| Data nested to an unknown depth | Very long lists (thousands of steps deep) |
| Divide-and-conquer algorithms such as merge sort | Code where speed matters most |
Common Mistakes
- Forgetting the base case, or writing one that is never reached, such as checking
n === 0whenncan jump past zero. - Not making the problem smaller. Calling
factorial(n)insidefactorial(n)loops forever. - Forgetting
returnbefore the recursive call, so the answer is calculated but thrown away. - Using recursion for very deep work, like a list of 100,000 items. JavaScript engines allow only about ten thousand nested calls, so use a loop.
Practice Exercises
Exercise 1. Write a recursive power(base, exp) that works for whole numbers 0 or more.
Show answer
function power(base, exp) {
if (exp === 0) return 1; // base case
return base * power(base, exp - 1); // smaller problem
}
console.log(power(2, 10)); // 1024
Exercise 2. Write reverse(str) recursively, so reverse("Dhaka") returns "akahD".
Show answer
function reverse(str) {
if (str.length <= 1) return str;
return reverse(str.slice(1)) + str[0];
}
Each call moves the first letter to the end of the reversed rest of the string.
Frequently Asked Questions
Is recursion slower than a loop?
Usually a little, because every call adds a frame to the call stack. For trees and nested data the difference rarely matters, and the recursive code is much shorter and clearer. For simple counting, a loop is faster and safer.
Can any recursive function be written as a loop?
Yes. A loop with your own stack (an array you push to and pop from) can do anything recursion can. This is how you process very deep data without hitting the call stack limit.
Summary
- A recursive function calls itself on a smaller problem until it reaches a base case.
- Each call waits on the call stack until the calls below it return.
- Recursion is the natural fit for trees and data nested to any depth.
- Memoise repeated work, and use a loop when the depth could be very large.
