Recursion, trees and heaps · core
Recursion in JavaScript
A recursive function solves a small base case directly and calls itself on a smaller input. In JavaScript every call waits on the call stack, deep calls throw RangeError, and Node does not optimise tail calls, so state the base case, the shrinking step and the depth limit.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- Three parts: base case, recursive case on a smaller input, combine the results.
- The call stack: each call keeps its own local variables until it returns; code after the recursive call runs on the way back up (post-order).
- Memoisation: cache results by argument (Map) when the same sub-call repeats (fib, grid paths). It turns exponential into polynomial time.
- Depth: about 10,000 frames in Node (varies by engine and frame size). For deep data, convert to iteration with an explicit stack.
- Common frontend uses: flatten nested arrays, deep clone (with a WeakMap for cycles), walk the DOM or a JSON tree, render nested comments or a file tree.
- Fast power: x^n = (x^(n/2))² — O(log n) calls; handle negative n with 1 / x^-n.
- Node and Chrome do not optimise tail calls (only Safari does), so rewriting a function as a tail call does not save stack in JavaScript. For deep inputs, use a loop with an explicit stack.
The red pen
Common traps: mistake → fix
Mistake: Recursion is always slower
Fix: it is often the clearest; the issue is depth and repeated work, not speed.
Mistake: A missing base case just returns undefined
Fix: it recurses until RangeError.
Mistake: Memoising with an object key like {a, b} works
Fix: objects compare by reference; build a string key.
Easy to hard
Questions interviewers ask, easy to hard
- Sum all numbers in a nested array.
- What is the space complexity of your recursion?
- Your input is nested 100,000 levels deep. What happens and how do you fix it?
- Compute fib(50) quickly. Why is plain recursion too slow?
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.