Recursion Programs
Recursion Programs — purpose and prerequisites
Recursion solves a problem by calling the same function on smaller inputs until a base case is reached. Each call consumes stack space, so recursion is not always the best solution for very deep inputs. Validate the input and guarantee the step moves toward the base case.
What you’ll learn
- Explain the purpose of recursion programs.
- Identify the typed contract, runtime responsibilities and common pitfalls.
- Run the example and extend its behavior with a practical exercise.
How the idea works
For 5, the calls calculate 5 × 4 × 3 × 2 × 1, returning 120. The 0! base case returns 1. An upper bound limits number precision problems.
Missing a base case or passing an input that does not approach it can cause unbounded recursion and a stack overflow.
Visualize the flow
Run the checked TypeScript example
This source was compiled using TypeScript 5.8.3 with strict checking, then executed with Node.js 22.16.0. Its stdout below is the actual captured output. The core logic is runnable without a framework or a remote API; integration-specific examples appear in a separate lab when needed.
TypeScript source
function factorial(n: number): number {
if (!Number.isSafeInteger(n) || n < 0 || n > 20) throw new Error("n must be 0..20");
if (n <= 1) return 1;
return n * factorial(n - 1);
}
console.log(factorial(0));
console.log(factorial(5));Verified output
1
120Compile: npx tsc --strict --target es2022 --module commonjs recursion-programs.ts; run: node recursion-programs.js. For examples importing node: modules, install @types/node as a development dependency; for browser or React projects use the separate lab setup.
Trace the execution
For 5, the calls calculate 5 × 4 × 3 × 2 × 1, returning 120. The 0! base case returns 1. An upper bound limits number precision problems.
Before editing the code, predict what the output will be for one changed input. Run it and compare your prediction with the actual result.
Common mistake and correction
Missing a base case or passing an input that does not approach it can cause unbounded recursion and a stack overflow.
Determine whether the issue belongs to the type system, a trust boundary, or actual runtime behavior before choosing a correction.
Your turn: extend the example
Implement the greatest common divisor recursively using Euclid's algorithm, then compare against a loop.
Record expected success and failure outcomes, run the code, and compare the observed behavior. Keep the exercise compatible with strict type checking.
Check your understanding
Key idea to remember
For 5, the calls calculate 5 × 4 × 3 × 2 × 1, returning 120. The 0! base case returns 1. An upper bound limits number precision problems.
Apply the same reasoning to the practice task, then integrate it into a real app only when the runtime and dependency setup are ready.
Reaching the recap and completing the quizzes are separate milestones.