Emmanuel Akinfulubi

JavaScriptMath

parseInt vs Number vs unary plus in JavaScript

Intermediate · 4 min read

Everything a user types into a web page arrives as text. A quantity field holding 42 gives you the string '42', not the number. Before you can add, compare or check it, you have to convert it, and JavaScript offers three common ways: Number(s), parseInt(s, 10) and the unary plus, +s.

They agree on clean input and disagree on messy input, like '42abc', '' or '1e3'. In this tutorial you will run all three on six strings, build a small table of the results, and learn which one to pick. You need to know arrays, map and Number.isNaN.

Strict or lenient

The three tools fall into two groups:

  • Strict: Number(s) and +s read the whole string. If any part isn't a number, the result is NaN ("Not a Number"). +s is just a short way to write Number(s).
  • Lenient: parseInt(s, 10) reads from the start for as long as it sees digits, then stops and ignores the rest. It only reads whole numbers.

The 10 in parseInt(s, 10) is the radix, the number base. 10 means ordinary decimal. Always pass it, so nobody has to guess.

Here is the exercise. Try it yourself first if you like, then read on and we will build it together.

20 parseInt, Number and unary plus

fair

Convert '42', '42abc', '0.9', '' and ' 12 ' to numbers three ways and tabulate what each does. Then find the one that reads '1e3' as 1.

Stuck? Three hints, smallest first
  1. 1. Number converts the whole string or gives NaN.
  2. 2. parseInt reads as far as it can and stops, so trailing rubbish is ignored.
  3. 3. parseInt also stops at the decimal point and at the e of exponential notation.

Step 1: clean input

Step 1

console.log(Number('42'));       // 42
console.log(parseInt('42', 10)); // 42
console.log(+'42');              // 42

On a plain number, all three give the same answer.

Step 2: trailing rubbish

Step 2

console.log(Number('42abc'));       // NaN
console.log(parseInt('42abc', 10)); // 42

Number sees abc and gives up. parseInt reads 42, hits a, and stops. That is useful for '12px', where you want the 12. It is harmful in a form field, where '42abc' is a typo you should reject rather than accept as 42.

Step 3: decimals and exponents

Step 3

console.log(Number('0.9'));       // 0.9
console.log(parseInt('0.9', 10)); // 0
console.log(Number('1e3'));       // 1000
console.log(parseInt('1e3', 10)); // 1

parseInt stops at the decimal point, so '0.9' becomes 0. It also stops at the e in '1e3', which is how JavaScript writes 1 times 10 to the 3rd. Number understands both, so it gives 0.9 and 1000. This answers the question in the task: parseInt is the one that reads '1e3' as 1.

Step 4: empty strings and spaces

Step 4

console.log(Number(''));        // 0
console.log(parseInt('', 10));  // NaN
console.log(Number('  12  '));  // 12
console.log(parseInt('  12  ', 10)); // 12

Spaces at the start and end are ignored by all three. But an empty string splits them: Number('') is 0, and parseInt('', 10) is NaN.

Number('') being 0 is the trap that lasts longest. A cleared field quietly becomes zero, and a zero total looks believable. Check the text first: s.trim() !== ''.

Step 5: build the table

Now run all three on every input with map, which turns each string into an object of results:

Step 5

const inputs = ['42', '42abc', '0.9', '', '  12  ', '1e3'];
const table = inputs.map((s) => ({
  input: JSON.stringify(s),
  number: Number(s),
  parseInt: parseInt(s, 10),
  plus: +s,
}));
console.log(table[1]); // { input: '"42abc"', number: NaN, parseInt: 42, plus: NaN }

JSON.stringify(s) wraps each input in double quotes, so you can see the empty string and the spaces in the output. The answer panel prints every row, and console.table(table) would show them as a grid in a browser.

Step 6: values that aren't strings

Number also converts other types, and a couple of the results are worth knowing:

Step 6

console.log(Number(null));      // 0
console.log(Number(undefined)); // NaN
console.log(Number(true));      // 1
console.log(Number([]));        // 0

A missing value, null, becomes 0, while undefined becomes NaN. Neither is an error, so check for them before you convert.

Picking one

  • Use Number(s) (or +s) for form fields and data you expect to be a complete number. Bad input becomes NaN, which you can catch with Number.isNaN.
  • Use parseInt(s, 10) when the text starts with a number and you want just that part, like '12px'.

The full solution

The answer panel builds the full table for all six inputs and prints each row, then converts null, undefined, true and []. The checks underneath confirm each difference, including that only parseInt reads '1e3' as 1. Press Run to see the output.

The answer

const inputs = ['42', '42abc', '0.9', '', '  12  ', '1e3'];

const table = inputs.map((s) => ({
  input: JSON.stringify(s),
  number: Number(s),
  parseInt: parseInt(s, 10),
  plus: +s,
}));

for (const row of table) console.log(row);

console.log('Number(null)      :', Number(null), 'Number(undefined):', Number(undefined));
console.log('Number(true)      :', Number(true), 'Number([])       :', Number([]));

Output


      
9 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('Number reads the whole string or fails', [Number('42'), Number.isNaN(Number('42abc'))], [42, true]);
test('parseInt reads as far as it can', parseInt('42abc', 10), 42);
test('parseInt stops at the decimal point', parseInt('0.9', 10), 0);
test('where Number keeps the fraction', Number('0.9'), 0.9);
test('unary plus is Number in one character', +'3.5', 3.5);
test('an empty string is 0 to Number but NaN to parseInt', [Number(''), Number.isNaN(parseInt('', 10))], [0, true]);
test('null is 0, undefined is NaN', [Number(null), Number.isNaN(Number(undefined))], [0, true]);
test('surrounding whitespace is trimmed by all of them', [Number('  12  '), parseInt('  12  ', 10), +'  12  '], [12, 12, 12]);
test('but only parseInt reads 1e3 as 1', [parseInt('1e3', 10), Number('1e3')], [1, 1000]);

Choose by what a bad input should do. Number and + are strict about the whole string, so "42abc" becomes NaN and you can reject it. parseInt is lenient by design — it exists to read a prefix, which is right for "12px" and wrong for a form field, where "42abc" silently becomes 42.

Number('') being 0 is the trap that outlives all the others. An empty input, an absent value, a cleared field: all become zero, and a zero total looks plausible. Validate the string before converting, or check s.trim() !== '' first.

Common mistakes

  • Using parseInt on form input. '42abc' becomes 42 with no complaint. Use Number and check for NaN.
  • Forgetting that Number('') is 0. An empty field passes as zero. Check s.trim() !== '' first.
  • Leaving out the radix. Write parseInt(s, 10). Without it, a string like '0x1A' is read as hexadecimal, base 16.

Try it yourself

  1. Write toQuantity(s) that returns a whole number, or null for empty, non-numeric or decimal input.
  2. Predict Number('1,000') and parseInt('1,000', 10), then run them.
  3. Use parseFloat('3.75kg') and compare it with parseInt('3.75kg', 10).

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.