Measure an environment's practical limit
Testing runtime behavior across browsers or JavaScript hosts.
JS Puzzles · Const
JavaScript engines cap the number of nested recursive calls because each call uses stack space. The exact limit varies by engine, and exceeding it can raise a maximum-stack-size error.
Each recursive call creates another execution context on the call stack, so deeper recursion consumes more memory. JavaScript engines impose a runtime-dependent maximum depth; exceeding it typically raises a stack-overflow error, making iteration preferable for very deep work.
function name(parameters) { /* recursive call */ }function recurse(depth) {
try {
recurse(depth + 1);
} catch (error) {
return depth;
}
}
console.log(recurse(0));This deliberately recurses until the runtime rejects another nested call; the reported depth varies by JavaScript engine, so it is for experimentation rather than production logic.
Testing runtime behavior across browsers or JavaScript hosts.
Processing deeply nested trees or graphs.
Designing recursive algorithms with bounded input.
Recursion depth is the maximum number of nested calls, counting the initial call. Each call adds an execution context to the stack, and the engine limits how many contexts can coexist.
Follow-up: What determines the exact limit? The JavaScript engine and its available stack configuration; code should not depend on a particular numeric threshold.
A recursive call creates another execution context, which consumes memory while callers wait to resume. Consequently, sufficiently deep recursion can exceed the stack and produce a maximum-stack-size error.
Follow-up: How would you handle very deep input? Rewrite the algorithm iteratively, often using an explicit stack or another loop-based worklist.
Tail-call optimization can avoid retaining the caller's execution context when the recursive call is the final operation. The documentation notes that support is not universal, so it cannot generally be relied on in JavaScript.
Follow-up: Does putting the recursive call last guarantee safety? No; the running engine must implement the optimization, and most engines do not.
recursion depthexecution contextstacktail call optimizationmaximum stack size exceeded