How do you convert a string to a number in JavaScript?
JavaScriptThe 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
// Number() — strict conversionNumber('42'); // 42Number('3.14'); // 3.14Number(''); // 0Number('hello'); // NaNNumber('42px'); // NaN — does not ignore trailing text// parseInt() — parses integers, ignores trailing textparseInt('42'); // 42parseInt('42px'); // 42 — stops at non-numeric characterparseInt('3.14'); // 3 — drops the decimalparseInt('0xFF', 16); // 255 — supports different bases// parseFloat() — parses decimals, ignores trailing textparseFloat('3.14'); // 3.14parseFloat('42px'); // 42parseFloat('3.14.15'); // 3.14 — stops at second dot// Unary + operator — same as Number()+'42'; // 42+'3.14'; // 3.14+''; // 0+'hello'; // NaNWhich 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 forNumber(), common in one-liners
Common gotchas
Number(null); // 0Number(undefined); // NaNNumber(true); // 1Number(false); // 0Number([]); // 0Number([1]); // 1Number([1, 2]); // NaNparseInt(''); // NaN (but Number('') is 0)parseInt('0x1F'); // 31 — parses as hex automaticallyAlways check for NaN after conversion:
const num = Number(userInput);if (Number.isNaN(num)) { console.log('Not a valid number');}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().