JavaScript Recursion: Base Case, Call Stack and Real Examples
Some problems contain smaller copies of themselves: a folder holds folders, a JSON response holds nested objects, a menu holds sub-menus. Recursion solves them by letting a function call itself on the smaller piece until it reaches a piece simple enough to answer directly. In this lesson you will learn how recursive functions work, how the call stack runs them, how to avoid the “Maximum call stack size exceeded” error, and how to use recursion on real nested data such as API responses and test configuration.
📖 What You’ll Learn: what recursion is, the base case and the recursive case, tracing calls on the call stack, classic examples (factorial, sum, countdown), stack overflow and RangeError, recursion versus loops, recursion on nested arrays and objects (flatten, deep search, deep count), memoizing slow recursion, and when not to use recursion.
🪞 What Is Recursion?
Definition: recursion is when a function calls itself. Every recursive function needs two parts:
- A base case: a simple input the function answers directly, without calling itself. This is what stops the recursion.
- A recursive case: the function calls itself with a smaller or simpler input that moves towards the base case.
📄 countdown.js
function countdown(n) {
if (n === 0) { // base case
console.log("Liftoff!");
return;
}
console.log(n);
countdown(n - 1); // recursive case: a smaller problem
}
countdown(3);
⌨️ Terminal
node countdown.js
🖥️ Output
3
2
1
Liftoff!
Each call handles one number and hands the rest of the work to a call with n - 1, until n reaches 0.
🧮 Classic Examples: Sum and Factorial
The sum of the numbers from 1 to n is n plus the sum from 1 to n - 1:
📄 classic.js
function sumTo(n) {
if (n <= 1) return n; // base case
return n + sumTo(n - 1); // recursive case
}
function factorial(n) {
if (n <= 1) return 1; // 0! and 1! are 1
return n * factorial(n - 1);
}
console.log(sumTo(5), sumTo(100));
console.log(factorial(5), factorial(10));
⌨️ Terminal
node classic.js
🖥️ Output
15 5050
120 3628800
Read factorial(5) as: 5 × factorial(4) = 5 × 4 × factorial(3) = … = 5 × 4 × 3 × 2 × 1 = 120.
📚 How It Runs: The Call Stack
Definition: the call stack is the list of function calls that have started but not finished. Each call is pushed on top of the stack; when it returns, it is popped off and the call below it continues.
This version prints each step so you can watch the stack grow and shrink:
📄 trace.js
function factorial(n, depth = 0) {
const pad = " ".repeat(depth);
console.log(`${pad}factorial(${n}) called`);
if (n <= 1) {
console.log(`${pad}base case -> 1`);
return 1;
}
const result = n * factorial(n - 1, depth + 1);
console.log(`${pad}factorial(${n}) returns ${result}`);
return result;
}
factorial(4);
⌨️ Terminal
node trace.js
🖥️ Output
factorial(4) called
factorial(3) called
factorial(2) called
factorial(1) called
base case -> 1
factorial(2) returns 2
factorial(3) returns 6
factorial(4) returns 24
- The calls go down until the base case: 4 → 3 → 2 → 1. All of them are waiting on the stack at that moment.
- Then the results come back up: 1, then 2 × 1, then 3 × 2, then 4 × 6.
- Every waiting call uses memory, which is why very deep recursion can run out of stack space.
💥 Stack Overflow: Maximum Call Stack Size Exceeded
If the base case is missing or never reached, the function calls itself until the stack is full, and JavaScript throws a RangeError:
📄 overflow.js
let calls = 0;
function brokenCountdown(n) {
calls++;
brokenCountdown(n - 1); // no base case: never stops
}
try {
brokenCountdown(3);
} catch (e) {
console.log(`${e.name}: ${e.message}`);
console.log("more than 1,000 nested calls before it failed?", calls > 1000);
}
⌨️ Terminal
node overflow.js
🖥️ Output
RangeError: Maximum call stack size exceeded
more than 1,000 nested calls before it failed? true
The exact number of calls before the crash depends on the engine and the machine, typically around ten thousand. Common causes:
- No base case, or a base case that cannot be reached (for example checking
n === 0whenncan go negative or be a decimal). - The recursive call does not make the problem smaller (calling
f(n)instead off(n - 1)). - Data with a cycle, such as an object that references itself, when walking nested objects.
- Legitimately very deep input (hundreds of thousands of levels). Use a loop instead.
💡 Tip: Make base cases defensive: if (n <= 0) is safer than if (n === 0), because it also stops for negative input.
🔁 Recursion vs Loops
Anything written recursively can also be written with a loop, and the reverse. Choose the one that matches the shape of the problem:
📄 vs-loop.js
// Same result, two styles
const sumRecursive = (n) => (n <= 0 ? 0 : n + sumRecursive(n - 1));
function sumLoop(n) {
let total = 0;
for (let i = 1; i <= n; i++) total += i;
return total;
}
console.log(sumRecursive(1000), sumLoop(1000));
try {
sumRecursive(100000); // too deep for the default stack
} catch (e) {
console.log("recursive:", e.name);
}
console.log("loop:", sumLoop(100000));
⌨️ Terminal
node vs-loop.js
🖥️ Output
500500 500500
recursive: RangeError
loop: 5000050000
| Use | When |
|---|---|
| A loop | Flat repetition: counting, walking an array, retrying. Very large or unknown depth. |
| Recursion | Nested, tree-shaped data: folders, menus, nested JSON, DOM trees, comment threads. Divide-and-conquer algorithms. |
📌 Note: JavaScript engines in practice do not optimise “tail calls”, so even a recursive call in the last position still uses a stack frame. Do not rely on recursion for depths in the tens of thousands.
🌳 Recursion on Nested Data
Recursion is the natural tool when data can contain more of the same data at any depth. Three common jobs:
Flatten a nested array
📄 flatten.js
function flatten(list) {
const result = [];
for (const item of list) {
if (Array.isArray(item)) {
result.push(...flatten(item)); // recurse into the nested array
} else {
result.push(item);
}
}
return result;
}
const suites = ["login", ["cart", ["add", "remove"]], [["checkout"]]];
console.log(flatten(suites));
console.log(suites.flat(Infinity)); // built-in equivalent
⌨️ Terminal
node flatten.js
🖥️ Output
[ 'login', 'cart', 'add', 'remove', 'checkout' ]
[ 'login', 'cart', 'add', 'remove', 'checkout' ]
Find all values of a key anywhere in a JSON object
📄 find-all.js
function findAll(data, key, found = []) {
if (Array.isArray(data)) {
for (const item of data) findAll(item, key, found);
} else if (data !== null && typeof data === "object") {
for (const [k, v] of Object.entries(data)) {
if (k === key) found.push(v);
findAll(v, key, found);
}
}
return found;
}
const response = {
order: { id: 501, items: [
{ id: 1, sku: "PEN-1", options: { colour: { id: "c-blue" } } },
{ id: 2, sku: "BOOK-9" },
] },
customer: { id: 77 },
};
console.log(findAll(response, "id"));
console.log(findAll(response, "sku"));
⌨️ Terminal
node find-all.js
🖥️ Output
[ 501, 1, 'c-blue', 2, 77 ]
[ 'PEN-1', 'BOOK-9' ]
Count items in a nested menu
📄 menu.js
const menu = [
{ label: "Tutorials", children: [
{ label: "JavaScript", children: [{ label: "Basics" }, { label: "Async" }] },
{ label: "Playwright" },
] },
{ label: "Practice" },
];
function countItems(items) {
let count = 0;
for (const item of items) {
count += 1;
if (item.children) count += countItems(item.children);
}
return count;
}
function printTree(items, depth = 0) {
for (const item of items) {
console.log(`${" ".repeat(depth)}- ${item.label}`);
if (item.children) printTree(item.children, depth + 1);
}
}
printTree(menu);
console.log("menu items:", countItems(menu));
⌨️ Terminal
node menu.js
🖥️ Output
- Tutorials
- JavaScript
- Basics
- Async
- Playwright
- Practice
menu items: 6
A UI test can use the same function to check that every menu link was rendered, whatever the depth of the menu.
⚡ Making Slow Recursion Fast: Memoization
Some recursive functions call themselves with the same input many times. The Fibonacci sequence is the classic example: fib(n) = fib(n - 1) + fib(n - 2).
📄 fibonacci.js
let calls = 0;
function fib(n) {
calls++;
if (n <= 1) return n;
return fib(n - 1) + fib(n - 2);
}
console.log(fib(25), "calls:", calls);
const memo = new Map();
let memoCalls = 0;
function fibMemo(n) {
memoCalls++;
if (n <= 1) return n;
if (memo.has(n)) return memo.get(n);
const value = fibMemo(n - 1) + fibMemo(n - 2);
memo.set(n, value);
return value;
}
console.log(fibMemo(25), "calls:", memoCalls);
console.log(fibMemo(70)); // instant with memoization
⌨️ Terminal
node fibonacci.js
🖥️ Output
75025 calls: 242785
75025 calls: 49
190392490709135
Storing results that were already calculated (memoization, see the Closures lesson) turns hundreds of thousands of calls into a few dozen.
🧪 Tester Scenario: Compare Two Nested Objects and Report Differences
When an API response differs from the expected data, a test should say exactly where. This recursive function walks both objects and reports each different path:
📄 diff.js
function diff(expected, actual, path = "$") {
const isObj = (v) => v !== null && typeof v === "object";
if (!isObj(expected) || !isObj(actual)) {
return Object.is(expected, actual) ? [] : [`${path}: expected ${JSON.stringify(expected)}, got ${JSON.stringify(actual)}`];
}
const keys = new Set([...Object.keys(expected), ...Object.keys(actual)]);
const problems = [];
for (const key of keys) {
const childPath = Array.isArray(expected) ? `${path}[${key}]` : `${path}.${key}`;
problems.push(...diff(expected[key], actual[key], childPath));
}
return problems;
}
const expected = { id: 7, user: { name: "Asha", roles: ["tester", "admin"] }, active: true };
const actual = { id: 7, user: { name: "Asha", roles: ["tester"] }, active: "true", extra: 1 };
const problems = diff(expected, actual);
console.log(problems.length === 0 ? "objects match" : problems.join("\n"));
⌨️ Terminal
node diff.js
🖥️ Output
$.user.roles[1]: expected "admin", got undefined
$.active: expected true, got "true"
$.extra: expected undefined, got 1
Test frameworks do this for you (toEqual prints a diff), but writing it once shows how recursion handles data of any shape.
📝 Practice Questions with Answers
Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.
Q1. Write a recursive power(base, exp) for whole, non-negative exponents.
Show answer
📄 practice1.js
function power(base, exp) {
if (exp <= 0) return 1;
return base * power(base, exp - 1);
}
console.log(power(2, 10), power(5, 0), power(3, 4));🖥️ Output
1024 1 81Q2. Write a recursive reverse(str) that reverses a string.
Show answer
📄 practice2.js
function reverse(str) {
if (str.length <= 1) return str;
return reverse(str.slice(1)) + str[0];
}
console.log(reverse("recursion"));🖥️ Output
noisrucerQ3. Write a recursive sumDigits(n) that adds the digits of a positive integer, e.g. sumDigits(4096) is 19.
Show answer
📄 practice3.js
function sumDigits(n) {
if (n < 10) return n;
return (n % 10) + sumDigits(Math.floor(n / 10));
}
console.log(sumDigits(4096), sumDigits(7));🖥️ Output
19 7Q4. Write a recursive isPalindrome(s) that ignores case.
Show answer
📄 practice4.js
function isPalindrome(s) {
s = s.toLowerCase();
if (s.length <= 1) return true;
if (s[0] !== s[s.length - 1]) return false;
return isPalindrome(s.slice(1, -1));
}
console.log(isPalindrome("Level"), isPalindrome("Racecar"), isPalindrome("Tester"));🖥️ Output
true true falseQ5. Write depth(value) that returns how deeply nested an array is: depth(5) is 0, depth([1]) is 1, depth([1, [2, [3]]]) is 3.
Show answer
📄 practice5.js
function depth(value) {
if (!Array.isArray(value)) return 0;
if (value.length === 0) return 1;
return 1 + Math.max(...value.map(depth));
}
console.log(depth(5), depth([1]), depth([1, [2, [3]]]), depth([]));🖥️ Output
0 1 3 1Q6. This function never stops for countdown(2.5). Explain why and make the base case safe.
function countdown(n) {
if (n === 0) return "done";
return countdown(n - 1);
}Show answer
2.5 → 1.5 → 0.5 → -0.5 … never equals 0, so the base case is never reached. Use a range check:
📄 practice6.js
function countdown(n) {
if (n <= 0) return "done";
return countdown(n - 1);
}
console.log(countdown(2.5), countdown(3), countdown(-4));🖥️ Output
done done done🧠 MCQ Quiz: Recursion
10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.
- What two parts must every recursive function have?Answer: A base case and a recursive case. The base case stops recursion; the recursive case moves towards it.
- What is factorial(4) with
f(n) = n <= 1 ? 1 : n * f(n - 1)?Answer: 24. 4 × 3 × 2 × 1. - Which error is thrown when recursion never stops?Answer: RangeError: Maximum call stack size exceeded. The call stack runs out of space.
- What is the call stack?Answer: The list of function calls that have started but not finished. Each call is pushed on, and popped when it returns.
- Which problem is the most natural fit for recursion?Answer: Walking a nested folder or JSON tree. Tree-shaped data has smaller copies of itself.
- Why is
if (n <= 0)often safer thanif (n === 0)as a base case?Answer: It also stops for negative or decimal inputs. An unreachable base case causes a stack overflow. - What does memoization do for recursive functions?Answer: Caches results so repeated inputs are not recalculated. fib with memoization needs far fewer calls.
- What does
[1, [2, [3, [4]]]].flat(Infinity)return?Answer: [1, 2, 3, 4]. flat(Infinity) flattens every level. - For summing numbers up to 1,000,000, which is safer?Answer: A loop. One million nested calls would overflow the stack.
- In
sumTo(n) = n + sumTo(n - 1), which happens first?Answer: All calls go down to the base case, then results are added on the way back. Each call waits for the smaller call’s result.
💼 Interview Questions and Answers
Q1. What is recursion, and what is a base case?
Recursion is a technique where a function solves a problem by calling itself on a smaller instance of the same problem. The base case is the condition under which the function returns a result directly without recursing; it guarantees termination. Each recursive call must move the input closer to the base case.
Q2. What causes “Maximum call stack size exceeded”, and how do you fix it?
Each pending call occupies a stack frame; when too many accumulate, the engine throws a RangeError. Causes: a missing or unreachable base case, a recursive call that does not shrink the input, cyclic data, or genuinely huge depth. Fixes: correct the base case (use ranges like <= 0), track visited objects for cyclic data, or rewrite the algorithm with a loop and an explicit stack.
Q3. Rewrite a recursive tree walk iteratively.
📄 iterative.js
const tree = { name: "root", children: [
{ name: "a", children: [{ name: "a1" }] },
{ name: "b" },
] };
function namesIterative(root) {
const stack = [root];
const names = [];
while (stack.length > 0) {
const node = stack.pop();
names.push(node.name);
for (const child of [...(node.children ?? [])].reverse()) stack.push(child);
}
return names;
}
console.log(namesIterative(tree));
⌨️ Terminal
node iterative.js
🖥️ Output
[ 'root', 'a', 'a1', 'b' ]
An explicit array replaces the call stack, so depth is limited only by memory. Pushing children in reverse keeps the same order as the recursive version.
Q4. When would you use recursion in test automation?
For any nested structure of unknown depth: comparing or searching nested JSON responses, walking nested menus or tree views to check every node, traversing folders of test data files, or flattening nested test configuration. For flat repetition such as retries and polling, a loop is simpler and safer.
❓ Frequently Asked Questions
🤔 Is recursion slower than a loop in JavaScript?
Usually a little, because each call has overhead and uses stack memory. For tree-shaped data the clarity is worth it; for large flat repetition use a loop.
🤔 How deep can recursion go in JavaScript?
It depends on the engine, stack size and how much each call stores; typically around ten thousand frames. Do not design code that relies on a specific limit.
🤔 Does JavaScript support tail call optimisation?
It is in the ES2015 specification, but V8 (Chrome and Node.js) and most engines do not implement it, so treat every recursive call as using a stack frame.
🤔 What is the difference between recursion and iteration?
Iteration repeats with a loop and keeps state in variables. Recursion repeats by calling the function again and keeps state on the call stack. Both can solve the same problems.
🏁 Summary
- A recursive function calls itself; it needs a base case that stops and a recursive case that makes the problem smaller.
- Calls wait on the call stack until the base case returns; results then flow back up.
- A missing or unreachable base case causes
RangeError: Maximum call stack size exceeded. - Use loops for flat or very deep repetition, and recursion for nested data such as JSON, menus and folders.
- Memoization removes repeated work in recursive functions such as Fibonacci.
Next, continue with Lesson 25: Strings and String Methods. This completes Module 4. Module 5 continues with strings and regular expressions.
🎬 Watch JavaScript and automation tutorials on YouTube!
Subscribe to SqaToolsByDY • Practice on sqatools.in