Advertisement
Advanced JavaScript, Numbers, Math & BigInt

Why is Number.parseFloat('123abc') valid but Number('123abc') returns NaN?

Short answer

parseFloat() parses as much of the leading numeric-looking text as it can and stops at the first invalid character, ignoring the rest. The Number() constructor, by contrast, requires the ENTIRE string to be a valid numeric representation, returning NaN if any part fails to parse.

Save JavaScript mock interview
Advertisement
AModel answer
parseFloat() parses as much of the leading numeric-looking text as it can and stops at the first invalid character, ignoring the rest. The Number() constructor, by contrast, requires the ENTIRE string to be a valid numeric representation, returning NaN if any part fails to parse.
parseFloat('123abc');  // 123
Number('123abc');       // NaN
parseFloat('  42.5px'); // 42.5
Real-world example
Extracting a numeric value from a CSS measurement string like '42.5px' using parseFloat().
Likely follow-ups
  • Why does this difference make Number() generally safer for strict input validation?
Related topics