Mateen Kiani
Published on Thu Jul 03 2025·4 min read
JavaScript often surprises developers with how it handles types. Converting a string into a number seems straightforward, yet nuances hide in plain sight. One often overlooked aspect is how different conversion methods handle whitespace, prefixes, or invalid characters. Ever wondered why parseInt("08")
sometimes returns NaN
or how to choose between Number()
and the unary plus operator?
The truth is, picking the right string-to-integer method can save hours of debugging. By understanding quirks like automatic radix detection, silent failures, or performance differences, you’ll write code that’s predictable and fast. Let’s dive in and explore these techniques so you can handle any string-to-int conversion with confidence.
The built-in parseInt()
function parses a string and returns an integer of the specified radix (base). Its signature is:
parseInt(string, [radix]);
Key points:
0x
prefixes can change behavior:
parseInt("08")
→ 0
(in older engines) or NaN
parseInt("0x10")
→ 16
It stops reading at the first non-digit character:
parseInt("123abc") // 123parseInt("abc123") // NaN
It ignores leading whitespace:
parseInt(" 42") // 42
Tips for safe usage:
Always specify the second argument to avoid ambiguous results.
Example:
const str = "1010";const num = parseInt(str, 2); // 10 in decimal
The Number()
constructor converts values to numbers, including strings. Its behavior differs from parseInt()
:
Number(value);
Features:
Converts the entire string or returns NaN
on failure:
Number("123") // 123Number("123abc") // NaN
Handles floats and scientific notation:
Number("3.14") // 3.14Number("1e3") // 1000
Trims whitespace automatically:
Number(" 56 ") // 56
When to use:
Use
Number()
when you want an all-or-nothing conversion without partial success.
A terse way to convert strings to numbers is the unary plus:
+string;
How it works:
Number(string)
under the hood.Examples:
+"123" // 123+"12.34" // 12.34+"1e2" // 100+"abc" // NaN
Pros and cons:
The unary plus is great for quick scripts or pipelines where brevity matters.
Even the best methods can stumble on odd inputs. Watch out for:
Empty strings:
parseInt("") // NaNNumber("") // 0+"" // 0
Leading zeros:
parseInt("08") // NaN without radix
Non-numeric suffixes or prefixes:
parseInt("123px") // 123Number("123px") // NaN
Negative numbers:
parseInt("-10") // -10Number("-10") // -10
Semicolon insertion traps such as:
return+"123"; // Automatic semicolon; returns undefined
Read more on does JavaScript need semicolons.
Whenever you face odd inputs, write small tests to see how your chosen method reacts.
When dealing with API responses or stored data, you often parse JSON:
const json = '{"age": "30"}';const obj = JSON.parse(json);
Once parsed, the property obj.age
is still a string. Convert it:
obj.age = parseInt(obj.age, 10);// orobj.age = +obj.age;
Working with nested data:
function normalizeUser(user) {return {...user,id: Number(user.id),score: parseInt(user.score, 10),};}
Learn more about JSON in what is JavaScript Object Notation (JSON).
If you run conversions in tight loops or high-frequency code, measure impact:
Number()
is close behind.parseInt()
can be slower due to parsing logic.Benchmark example:
console.time('plus');for (let i=0; i<1e6; i++) { +"123"; }console.timeEnd('plus');console.time('num');for (let i=0; i<1e6; i++) { Number("123"); }console.timeEnd('num');console.time('parse');for (let i=0; i<1e6; i++) { parseInt("123", 10); }console.timeEnd('parse');
Practical tips:
Always profile before optimizing prematurely.
Converting JavaScript strings to integers is more than a one-size-fits-all task. You can choose parseInt()
for partial parsing, Number()
for strict conversion, or the unary plus for concise code. Watch out for edge cases like empty strings, leading zeros, or semicolon pitfalls. When working with JSON data, convert properties after parsing and validate the results. Finally, if performance matters, test each method in your environment. Armed with these tips, you’ll handle any string-to-int conversion cleanly and confidently.
Convert a JavaScript string to an integer using parseInt(), Number(), or unary plus operator, ensuring accurate number conversion in code.