Curriculum Series

How do you convert a string to a number in JavaScript?

How do you convert a string to a number in JavaScript?

How do you convert a string to a number in JavaScript?

JavaScript

The short answer

The most common ways are Number(), parseInt(), parseFloat(), and the unary + operator. Each behaves slightly differently with edge cases like empty strings, whitespace, and non-numeric characters.

The methods

JAVASCRIPT
1// Number() — strict conversion
2Number('42'); // 42
3Number('3.14'); // 3.14
4Number(''); // 0
5Number('hello'); // NaN
6Number('42px'); // NaN — does not ignore trailing text
7
8// parseInt() — parses integers, ignores trailing text
9parseInt('42'); // 42
10parseInt('42px'); // 42 — stops at non-numeric character
11parseInt('3.14'); // 3 — drops the decimal
12parseInt('0xFF', 16); // 255 — supports different bases
13
14// parseFloat() — parses decimals, ignores trailing text
15parseFloat('3.14'); // 3.14
16parseFloat('42px'); // 42
17parseFloat('3.14.15'); // 3.14 — stops at second dot
18
19// Unary + operator — same as Number()
20+'42'; // 42
21+'3.14'; // 3.14
22+''; // 0
23+'hello'; // NaN

Which one to use

  • Number() — when you want strict conversion (reject anything that is not purely a number)
  • parseInt() — when you need an integer and want to ignore trailing text (like '42px')
  • parseFloat() — when you need a decimal and want to ignore trailing text
  • + operator — shorthand for Number(), common in one-liners

Common gotchas

JAVASCRIPT
1Number(null); // 0
2Number(undefined); // NaN
3Number(true); // 1
4Number(false); // 0
5Number([]); // 0
6Number([1]); // 1
7Number([1, 2]); // NaN
8
9parseInt(''); // NaN (but Number('') is 0)
10parseInt('0x1F'); // 31 — parses as hex automatically

Always check for NaN after conversion:

JAVASCRIPT
1const num = Number(userInput);
2if (Number.isNaN(num)) {
3 console.log('Not a valid number');
4}

Use Number.isNaN(), not the global isNaN(). The global isNaN('hello') returns true because it coerces the string first, while Number.isNaN('hello') returns false (it only returns true for actual NaN values).

Interview Tip

Show Number(), parseInt(), and parseFloat() with the same inputs to highlight the differences. The '42px' example is the clearest differentiator — Number returns NaN, parseInt returns 42. Mentioning Number.isNaN vs isNaN is a good bonus.

Why interviewers ask this

This tests basic JavaScript knowledge about type conversion. Interviewers want to see if you know the different methods and their edge cases, especially the difference between Number() and parseInt().

Finished reading?

Mark this topic as solved to track your progress.