TheAlgorithms/JavaScript · error · TypeError
Expected a valid real number
Error message
Expected a valid real number
What it means
The isDivisible function checks whether num1 is evenly divisible by num2. The guard rejects NaN, Infinity, and -Infinity for either argument using Number.isFinite, since divisibility is only defined for finite real numbers. Notably, division by zero returns false rather than throwing an error.
Source
Thrown at Maths/IsDivisible.js:5
// Checks if a number is divisible by another number.
export const isDivisible = (num1, num2) => {
if (!Number.isFinite(num1) || !Number.isFinite(num2)) {
throw new TypeError('Expected a valid real number')
}
if (num2 === 0) {
return false
}
return num1 % num2 === 0
}
// isDivisible(10, 5) // returns true
// isDivisible(123498175, 5) // returns true
// isDivisible(99, 5) // returns false
View on GitHub (pinned to 5c39e87a9a)
Solutions
- Validate both numbers are finite (Number.isFinite) before calling.
- Sanitize parsed input that might be NaN before invoking.
- Coerce or reject null/undefined values upstream.
Example fix
// before isDivisible(parseFloat(str), 5) // after const n = Number(str) if (!Number.isFinite(n)) return false isDivisible(n, 5)
Defensive patterns
Strategy: validation
Validate before calling
if (!Number.isFinite(num1) || !Number.isFinite(num2)) {
return false
}
isDivisible(num1, num2) Type guard
const isFiniteNumber = (n) => typeof n === 'number' && Number.isFinite(n)
Prevention
- Check Number.isFinite before divisibility tests to catch NaN and Infinity.
- Sanitize parseFloat results for NaN before passing to arithmetic functions.
- Coerce or reject null/undefined values at data entry points.
When it happens
Trigger: Calling isDivisible(NaN, 5), isDivisible(10, Infinity), or passing undefined/null (Number.isFinite returns false for both). Results of parseFloat on unparseable strings also trigger it.
Common situations: Passing results of parseFloat on bad input, unchecked arithmetic that produced Infinity, values from JSON that were null, or undefined from missing object properties.
Related errors
- Not a Number
- The two parameters must be distinct, non-null integers
- Arguments must be numbers
- Number must be greater than zero.
- Input data must be numbers
AI-assisted analysis of TheAlgorithms/JavaScript@5c39e87a9a (2026-08-13).
Data as JSON: /api/errors/f527440fe57b2cff.
Report an issue: GitHub.