TheAlgorithms/JavaScript · error · RangeError
Input should be a non-negative whole number
Error message
Input should be a non-negative whole number
What it means
Thrown by `factorial(n)` (recursive) when `!Number.isInteger(n) || n < 0`. This is a `RangeError` (not TypeError), and it correctly catches NaN, floats, negatives, and non-numbers in one check because `Number.isInteger` is false for all of those. This is the most thorough input guard in the set.
Source
Thrown at Recursive/Factorial.js:13
/**
* @function Factorial
* @description function to find factorial using recursion.
* @param {Integer} n - The input integer
* @return {Integer} - Factorial of n.
* @see [Factorial](https://en.wikipedia.org/wiki/Factorial)
* @example 5! = 1*2*3*4*5 = 120
* @example 2! = 1*2 = 2
*/
const factorial = (n) => {
if (!Number.isInteger(n) || n < 0) {
throw new RangeError('Input should be a non-negative whole number')
}
if (n === 0) {
return 1
}
return n * factorial(n - 1)
}
export { factorial }
View on GitHub (pinned to 5c39e87a9a)
Solutions
- Validate `Number.isInteger(n) && n >= 0` upstream (matches the function's own guard).
- Coerce integer-like strings with `Number(n)` and check `Number.isInteger`.
- For large n, prefer an iterative factorial to avoid stack overflow - the recursive version has no guard against deep recursion.
Example fix
// before
factorial(userInput) // userInput could be -1 or 3.5
// after
const n = Number(userInput)
if (!Number.isInteger(n) || n < 0) throw new RangeError('n must be a non-negative integer')
factorial(n) Defensive patterns
Strategy: validation
Validate before calling
const n = Number(input)
if (!Number.isInteger(n) || n < 0) {
throw new RangeError('n must be a non-negative integer')
}
factorial(n) Type guard
const isNonNegativeInt = (x) => typeof x === 'number' && Number.isInteger(x) && x >= 0
Prevention
- The library's own guard (Number.isInteger + n >= 0) is the model - mirror it upstream.
- For large n, switch to an iterative factorial to avoid stack overflow.
- Coerce string input with Number() and re-check integrality.
When it happens
Trigger: Call `factorial(-1)`, `factorial(3.5)`, `factorial(NaN)`, `factorial('5')`, `factorial(undefined)`, `factorial(Infinity)`. All non-negative integers (including 0, which returns 1) pass.
Common situations: Floating-point math producing a non-integer by accident, negative numbers from sign errors, or unguarded user input.
Related errors
- The ${noName} only accepts positive values
- No natural numbers exist below 1
- Fibonacci sequence limit can't be less than 1
- Error size should be less than equal to 32
- Capacity should be greater than 0
AI-assisted analysis of TheAlgorithms/JavaScript@5c39e87a9a (2026-08-13).
Data as JSON: /api/errors/bc851587b27700ea.
Report an issue: GitHub.