Description
A recursive function that calls itself without a clear termination condition may exhaust the call stack or run indefinitely, depending on its input. Externally reachable call paths may also affect service availability according to the input and request volume.
Potential impact
- Stack exhaustion or endless execution may interrupt the program.
- Processing time and resource use may become difficult to predict across the input range.
Remediation
- Check the termination condition and input range before recursing.
- Limit recursion depth or use an iterative implementation.
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);
}
Explanation:
- Before: No termination condition stops the recursive calls, so execution may exhaust the stack.
- After: The function validates the input range and stops at the base case. The example limit of 18 keeps the factorial within the safe integer range of
Number. Use an appropriate numeric representation and resource limits if larger integers are required.