What is recursion in JavaScript and how to use it safely
· Category: JavaScript
Short answer
Recursion is when a function calls itself to solve smaller subproblems. A proper base case is required to stop the recursion and prevent infinite loops.
Steps
- Define a base case to terminate recursion:
javascript function factorial(n) { if (n <= 1) return 1; // base case return n * factorial(n - 1); } - Ensure progress toward the base case in every call.
- Use tail recursion when possible to help engines optimize stack usage:
javascript function factorialTail(n, acc = 1) { if (n <= 1) return acc; return factorialTail(n - 1, n * acc); } - For deep recursion, convert to an iterative loop or use a trampoline.
Tips
- Always validate inputs to avoid unexpected infinite recursion.
- Keep recursive solutions simple; complex mutual recursion is hard to debug.
Common issues
- Missing base case causes
RangeError: Maximum call stack size exceeded. - JavaScript engines do not universally optimize tail calls, so deep recursion can still overflow.