TheAlgorithms/JavaScript · error · TypeError
argument is not a Number
Error message
argument is not a Number
What it means
Thrown by RGBToHex when any of r, g, or b is not of type 'number'. The guard checks all three with typeof; a single non-number argument (including NaN, which is technically typeof 'number' and will pass) triggers it. It is a TypeError.
Source
Thrown at Conversions/RGBToHex.js:3
function RGBToHex(r, g, b) {
if (typeof r !== 'number' || typeof g !== 'number' || typeof b !== 'number') {
throw new TypeError('argument is not a Number')
}
const toHex = (n) => (n || '0').toString(16).padStart(2, '0')
return `#${toHex(r)}${toHex(g)}${toHex(b)}`
}
export { RGBToHex }
// > RGBToHex(255, 255, 255)
// '#ffffff'
// > RGBToHex(255, 99, 71)
// '#ff6347'
View on GitHub (pinned to 5c39e87a9a)
Solutions
- Coerce channels with Number(...) or parseInt(..., 10) before calling.
- Type-check all three in the caller: [r,g,b].every(v => typeof v === 'number' && !Number.isNaN(v)).
- Keep a single source of truth for color values as numbers.
Example fix
// before
RGBToHex('255', 99, 71)
// after
RGBToHex(Number('255'), 99, 71) Defensive patterns
Strategy: type-guard
Validate before calling
if (![r, g, b].every((v) => typeof v === 'number' && !Number.isNaN(v))) {
throw new TypeError('r, g, b must all be finite numbers')
}
RGBToHex(r, g, b) Type guard
const areRgbNumbers = (r, g, b) => [r, g, b].every((v) => typeof v === 'number' && !Number.isNaN(v))
Try / catch
try {
RGBToHex(r, g, b)
} catch (e) {
if (e instanceof TypeError && /not a Number/.test(e.message)) {
return RGBToHex(Number(r), Number(g), Number(b))
}
throw e
} Prevention
- Parse string channels with Number(...) or parseInt(..., 10) at the boundary.
- Remember NaN passes typeof === 'number', so also check Number.isNaN.
- Keep color values as numbers throughout your pipeline.
When it happens
Trigger: Calling RGBToHex('255', 0, 0) (r is a string), RGBToHex(null, 0, 0), or RGBToHex(undefined, 128, 128). Note NaN passes the guard because typeof NaN === 'number' — the function does not range-check.
Common situations: Reading color channels from a form/JSON where they arrive as strings; passing a value that was never initialized (undefined); mixing a defaulted optional channel.
Related errors
- Only string arguments are allowed
- Argument is not a string type
- Argument is not a string.
- Input is not a valid RGB color.
- hue should be between 0 and 360
AI-assisted analysis of TheAlgorithms/JavaScript@5c39e87a9a (2026-08-13).
Data as JSON: /api/errors/5fb85814e1ec59bc.
Report an issue: GitHub.