Why doesn't recursion go on forever?
The call stack, every call's own variables, and why trees ask for recursion.
factorial(5) calmly return 120 instead of flying off into eternity?The secret is the call stack. When a function calls another function (or itself), it gets paused and waits for the answer. The JavaScript engine writes down: "here's a call that's waiting, here's the line to come back to". These notes pile up: last in, first out. It's the same stack as push and pop on an array — the engine just keeps it for you.
An important detail: every call has its own variables. n in factorial(5) and n in factorial(4) are different variables, like different boxes on a shelf. That's why a nested call can't mess up the data of the call waiting for it.
function factorial(n, indent) {
console.log(indent + "enter: n = " + n);
if (n <= 1) {
console.log(indent + "bottom! returning 1");
return 1;
}
const result = n * factorial(n - 1, indent + " ");
console.log(indent + "exit: n = " + n + ", returning " + result);
return result;
}
factorial(4, "");n while it waits.Now the answer to the big question. Recursion isn't endless because every step shrinks the problem, and the base case makes no new call. Once it's reached, the pile starts to unwind: the top call returns its answer and comes off the stack, the call waiting beneath it carries on — and so on, all the way down to the first one.
And if there's no base case — or the step doesn't get closer to it? Then the pile grows until it runs out of room. The call stack is limited: usually on the order of ten thousand calls, and the exact number depends on the browser and on how many variables the function has. The engine doesn't wait for eternity: it throws RangeError: Maximum call stack size exceeded. So "infinite" recursion in JavaScript isn't a hang — it's a quick crash.
let depth = 0;
function dive() {
depth += 1;
dive();
}
try {
dive();
} catch (error) {
console.log("The stack survived this many calls: " + depth);
}So why do trees love recursion so much? Look at the definition: a folder is files and folders. The definition refers to itself! Code that follows the shape of the data refers to itself too: "a folder's size is the sum of its files' sizes and the sizes of its subfolders". A loop can do it as well, but it has to keep its own pile of "what's not opened yet" by hand — something recursion gets from the call stack for free.
const folder = {
files: [10, 20],
folders: [
{ files: [5], folders: [] },
{ files: [], folders: [{ files: [1], folders: [] }] },
],
};
function sizeOf(f) {
let total = 0;
for (const file of f.files) total += file;
for (const sub of f.folders) total += sizeOf(sub);
return total;
}
function sizeWithLoop(root) {
const todo = [root];
let total = 0;
while (todo.length > 0) {
const f = todo.pop();
for (const file of f.files) total += file;
todo.push(...f.folders);
}
return total;
}
console.log(sizeOf(folder));
console.log(sizeWithLoop(folder));todo pile ourselves.Myth or fact?
Decide whether the statement is true. Got it wrong? Try again; once you're right, Byte explains what's going on.