gotchajavascriptModeratepending
Gotcha: JavaScript parseInt with radix surprises
Viewed 0 times
parseIntradixNumberparsingNaNconversion
Error Messages
Problem
parseInt behaves unexpectedly with certain inputs: leading zeros, non-numeric strings, and missing radix.
Solution
Always specify the radix and consider alternatives:
// Surprising behaviors:
parseInt('08') // 8 (OK in modern JS, was 0 in old engines with octal)
parseInt('0x10') // 16 (hex prefix detected)
parseInt('123abc') // 123 (stops at first non-numeric)
parseInt('') // NaN
parseInt('Infinity') // NaN
// Always specify radix:
parseInt('08', 10) // 8
// Better alternatives:
Number('123abc') // NaN (stricter)
Number('08') // 8
+'08' // 8 (unary plus, strict conversion)
// For floating point:
parseFloat('3.14rest') // 3.14 (still lenient)
Number('3.14rest') // NaN (strict)
// Surprising behaviors:
parseInt('08') // 8 (OK in modern JS, was 0 in old engines with octal)
parseInt('0x10') // 16 (hex prefix detected)
parseInt('123abc') // 123 (stops at first non-numeric)
parseInt('') // NaN
parseInt('Infinity') // NaN
// Always specify radix:
parseInt('08', 10) // 8
// Better alternatives:
Number('123abc') // NaN (stricter)
Number('08') // 8
+'08' // 8 (unary plus, strict conversion)
// For floating point:
parseFloat('3.14rest') // 3.14 (still lenient)
Number('3.14rest') // NaN (strict)
Why
parseInt is lenient by design — it parses as much as it can. For strict conversion, use Number() or the unary plus operator.
Revisions (0)
No revisions yet.