Recursive functions and termination
Quick answer
Recursion is when a function invokes itself directly or through other functions. A base case stops the chain of calls, while a recursive case moves toward that base.
How it works
For nonnegative bounded integers, sum(n) can return zero at n=0 or n + sum(n - 1). Each pending call waits for a smaller call to return. Recursion consumes call resources; a large input can exceed runtime limits.
function sum(n) { if (n === 0) return 0; return n + sum(n - 1); }console.log(sum(0), sum(4));Expected output in Node.js:
0 10The base case contributes zero, then pending additions unwind.
function power2(n) { if (n === 0) return 1; return 2 * power2(n - 1); }console.log(power2(3), power2(5));Expected output in Node.js:
8 32Multiplication uses one as its base result.
Common mistakes
A base case alone is insufficient if input never reaches it. Restrict the domain or validate it; do not assume arbitrary recursion depth is safe.
Practice
Trace sum(3) by writing pending additions and their results.