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.
parseInt Essentials
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:
- Always pass a radix. Without it, leading zeros or
0x
prefixes can change behavior:-
parseInt("08")
→0
(in older engines) orNaN
-
parseInt("0x10")
→16
-
- It stops reading at the first non-digit character:
parseInt("123abc") // 123
parseInt("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
Number Function
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") // 123
Number("123abc") // NaN
- Handles floats and scientific notation:
Number("3.14") // 3.14
Number("1e3") // 1000
- Trims whitespace automatically:
Number(" 56 ") // 56
When to use:
- You need strict conversion: no partial reads.
- You expect floats or exponential formats.
Use
Number()
when you want an all-or-nothing conversion without partial success.
Unary Plus Operator
A terse way to convert strings to numbers is the unary plus:
+string;
How it works:
- Equivalent to
Number(string)
under the hood. - Very concise, but can hurt readability for some teams.
Examples:
+"123" // 123
+"12.34" // 12.34
+"1e2" // 100
+"abc" // NaN
Pros and cons:
- Pro: Shortest syntax.
- Con: Might confuse readers unfamiliar with the operator.
The unary plus is great for quick scripts or pipelines where brevity matters.
Handling Edge Cases
Even the best methods can stumble on odd inputs. Watch out for:
- Empty strings:
parseInt("") // NaN
Number("") // 0
+"" // 0
- Leading zeros:
parseInt("08") // NaN without radix
- Non-numeric suffixes or prefixes:
parseInt("123px") // 123
Number("123px") // NaN
- Negative numbers:
parseInt("-10") // -10
Number("-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.
Working with JSON Data
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);
// or
obj.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).
Performance Tips
If you run conversions in tight loops or high-frequency code, measure impact:
- Generally, unary plus is fastest.
-
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:
- Cache conversions outside loops where possible.
- Use typed arrays or WebAssembly if you need bulk numeric transforms.
Always profile before optimizing prematurely.
Conclusion
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.
Top comments (2)
I think your benchmarking code is getting optimized away into nothingness (Chrome 137):
Those don't look plausible numbers for a million iterations of parsing a string to an integer, so more likely V8 has either figured out that the result is discarded and not bothered to calculate it, or has cached the results as it's always the same input so only needs to be calculated once, or both.
A better benchmark would be something like this:
Results aren't super stable for me (sometimes
plus
wins, sometimesnum
wins), butparseInt
definitely seems a little slower. Typical results forITERATIONS = 1e7
are something like this:Good catch. I agree your approach for benchmarking is better as it's using random numbers instead of same number Everytime.
BTW what results do you get with 1e6 as I see you are using 1e7.
Also for and for of loop might also have some slight impact on scores.