Recursive calls without a termination condition

Recursive calls without a termination condition

Description

A recursive function needs to reach its base case for every accepted input. Excessively deep calls can exhaust the stack.

Potential impact

A computation that never finishes or runs too long can interrupt the task and delay other requests.

Remediation

Validate the input and test the base case before recursing. Bound the call depth or use a loop with a limit on the work it performs.

Examples

Before

javascript
function factorial(x) {
  return x * factorial(x - 1);
}

After

javascript
function factorial(x) {
  if (!Number.isInteger(x) || x < 0 || x > 18) {
    throw new RangeError("unsupported input");
  }
  if (x <= 1) {
    return 1;
  }
  return x * factorial(x - 1);
}

The example accepts integers from 0 through 18 and returns 1 at 0 or 1. Factorials in this range fit within the safe integer range of Number. For larger inputs, choose an appropriate numeric type and bound the computation.

References