Hiprup

What is the difference between Number() and parseInt()?

Both convert strings to numbers, but parse differently.

  • Number() — converts the whole string; any invalid character gives NaN, so "12px" → NaN.

  • parseInt() — reads leading digits and stops at the first invalid one, so "12px" → 12. Pass a radix (usually 10).

  • parseFloat() — like parseInt but keeps decimals.

Choose: Number() for clean numeric strings; parseInt/parseFloat to extract a number from mixed text.

// Number() — full conversion
console.log(Number('42'));      // 42
console.log(Number('42.5'));    // 42.5
console.log(Number('42px'));    // NaN (entire string not numeric)
console.log(Number(''));        // 0
console.log(Number(true));      // 1
console.log(Number(null));      // 0
console.log(Number(undefined)); // NaN

// parseInt() — parse from start
console.log(parseInt('42'));      // 42
console.log(parseInt('42.5'));    // 42 (drops decimal)
console.log(parseInt('42px'));    // 42 (stops at 'p')
console.log(parseInt('px42'));    // NaN (starts with non-digit)
console.log(parseInt('0xFF', 16)); // 255 (hex)

// parseFloat() — parse with decimals
console.log(parseFloat('42.5px')); // 42.5

// Unary + (same as Number)
console.log(+'42');     // 42
console.log(+'42px');   // NaN
console.log(+'');       // 0

Number converts the ENTIRE value — '42px' fails because 'px' is not numeric. parseInt parses from the START — '42px' succeeds because it stops at 'p'. parseInt drops decimals; parseFloat preserves them. Number('') = 0 but parseInt('') = NaN.

The unary + is shorthand for Number().

Key difference: Number requires the entire string to be numeric, parseInt stops at the first non-digit. '42px': Number = NaN, parseInt = 42. Always pass radix to parseInt (parseInt('42', 10)).

The unary + trick is concise but less readable.

What is the difference between Number() and parseInt()? | Hiprup