The JavaScript parseInt() method
The parseInt() function parses a string and returns an integer, reading digits until it hits a non-digit. parseInt("42px", 10) is 42. Always pass 10 as the second argument (the radix) so it parses in base 10. It returns NaN if the string doesn't start with a number.
Overview
parseInt() turns the start of a string into a whole number. Its party trick is that it reads as far as it can and then stops at the first character that isn't part of a number, so parseInt("42px", 10) happily returns 42 — useful for pulling a number out of a value like a CSS length. If the string doesn't begin with a digit, it returns NaN.
The one rule you should never skip: always pass the radix, the base, as the second argument — almost always 10. Without it, parseInt() tries to guess the base from the string, and a leading 0x is treated as hexadecimal. Passing 10 explicitly removes any ambiguity and is considered best practice. Its sibling parseFloat() does the same job for decimals.
How does it differ from Number(str)? Number() is stricter — it converts the whole string or returns NaN, so Number("42px") is NaN. parseInt() is lenient and grabs the leading number. Use Number() (or the unary +) when the entire string should be a clean number, and parseInt() when you want to extract a leading integer.
Syntax
parseInt(string, radix)
parseInt("42", 10) // 42
parseInt("42px", 10) // 42 (stops at 'p')
parseInt("ff", 16) // 255 (hexadecimal)
parseInt("abc", 10) // NaN
Parameters
The parseInt() method accepts the following parameters.
| Parameter | Description |
|---|---|
string |
The value to parse. Leading whitespace is ignored; parsing stops at the first invalid character. |
radix |
The base (2-36) to parse in. Always pass 10 for ordinary decimal numbers. |
Example
<pre id="out" style="font:15px ui-monospace,monospace"></pre>
<script>
const width = '120px';
const n = parseInt(width, 10);
document.getElementById('out').textContent =
'parsed: ' + n + '\n' +
'doubled: ' + (n * 2) + 'px'; // parsed: 120 / doubled: 240px
</script>
Best practices
- Always pass the radix — usually
parseInt(str, 10)— to avoid ambiguous base guessing. - Use
parseInt()to extract a leading integer (like42from"42px"). - Use
Number()or unary+when the whole string must be a clean number. - Check the result with Number.isNaN(), since invalid input returns
NaN.
Frequently asked questions
Why should I always pass a radix to parseInt()?
parseInt() guesses the base from the string, which can misread values. Passing 10 guarantees decimal parsing.What is the difference between parseInt() and Number()?
parseInt() reads the leading number and ignores trailing text ("42px" → 42); Number() requires the whole string to be a valid number or returns NaN.How do I extract a number from a string like "42px"?
parseInt("42px", 10), which returns 42 by stopping at the first non-digit.What does parseInt() return for non-numeric strings?
NaN, if the string doesn't start with a parseable number.