TheAlgorithms/JavaScript · error · Error
The ${noName} only accepts positive values
Error message
The ${noName} only accepts positive values What it means
The second branch of the shared `isNumber` helper: thrown when the argument IS a number but is negative (`< 0`) or non-finite (NaN, +/-Infinity). Because volumes require positive radii/lengths, the helper rejects these. Note Infinity passes the typeof check then fails here, not in the TypeError branch.
Source
Thrown at Maths/Volume.js:119
isNumber(radius, 'Radius')
return (4 / 3) * Math.PI * radius ** 3
}
/*
Calculate the volume for a Hemisphere
Reference: https://www.cuemath.com/measurement/volume-of-hemisphere/
return (2 * PI * radius^3)/3
*/
const volHemisphere = (radius) => {
isNumber(radius, 'Radius')
return (2.0 * Math.PI * radius ** 3) / 3.0
}
const isNumber = (number, noName = 'number') => {
if (typeof number !== 'number') {
throw new TypeError('The ' + noName + ' should be Number type')
} else if (number < 0 || !Number.isFinite(number)) {
throw new Error('The ' + noName + ' only accepts positive values')
}
}
export {
volCuboid,
volCube,
volCone,
volPyramid,
volCylinder,
volTriangularPrism,
volPentagonalPrism,
volSphere,
volHemisphere
}
View on GitHub (pinned to 5c39e87a9a)
Solutions
- Validate `Number.isFinite(x) && x >= 0` before calling.
- Reject or clamp negative inputs at the form/validation layer.
- Guard against NaN explicitly - `typeof === 'number'` does not exclude it.
Example fix
// before
volHemisphere(parsedRadius) // parsedRadius could be -5 or NaN
// after
if (!Number.isFinite(parsedRadius) || parsedRadius < 0) {
throw new RangeError('radius must be a non-negative finite number')
}
volHemisphere(parsedRadius) Defensive patterns
Strategy: validation
Validate before calling
if (!Number.isFinite(radius) || radius < 0) {
throw new RangeError('radius must be a non-negative finite number')
}
volHemisphere(radius) Type guard
const isPositiveFinite = (x) => typeof x === 'number' && Number.isFinite(x) && x >= 0
Prevention
- typeof === 'number' is not enough - also exclude NaN and Infinity.
- Clamp or reject negative dimensions at the UI layer.
- Treat NaN as 'invalid input', not as 'zero'.
When it happens
Trigger: Call `volHemisphere(-5)`, `volCylinder(NaN, 10)`, `volSphere(Infinity)`, `volCone(3, -2)`. Negative dimensions or non-finite numeric values trigger it.
Common situations: Sign errors in user input (negative lengths), parsing failures that produce NaN before reaching the function, or unbounded computations (`1/0`) forwarded as a radius.
Related errors
- Cannot normalize vectors of length 0
- The ${noName} should be Number type
- No natural numbers exist below 1
- Fibonacci sequence limit can't be less than 1
- Dimension must be positive
AI-assisted analysis of TheAlgorithms/JavaScript@5c39e87a9a (2026-08-13).
Data as JSON: /api/errors/e77c4abaddfeafb4.
Report an issue: GitHub.