skip to content

In JavaScript, why does parseInt read the page parameters `2abc` as 2 and `1e3` as 1, and how does Number differ?

level: middleimportance: should knowfreq 47%

answer

  1. reads a prefix, then stops
  2. the whole string or nothing
  3. e is not a decimal digit
  4. the empty string splits them
  5. only one prefix without a radix

basics

~20 s

parseInt reads digits from the start and silently stops at the first invalid character, so 2abc gives 2 and 1e3 gives 1. Number converts the whole string or returns NaN, giving NaN and 1000 here.

solid answer

~40 s

`parseInt` converts its argument to a string, skips leading whitespace, takes an optional sign, then reads digits valid in the radix and ignores everything from the first invalid character. So `parseInt('2abc', 10)` is `2` and `parseInt('1e3', 10)` is `1`: no error, just a plausible wrong page. `Number` treats the whole trimmed string as a numeric literal, so `Number('2abc')` is `NaN` and `Number('1e3')` is `1000`. The empty string splits them too: `parseInt('')` is `NaN`, `Number('')` is `0`. Without a radix, `parseInt` assumes 16 for a `0x` prefix and 10 otherwise, so `?page=0x10` becomes page 16 unless you pass `10`; a leading zero is not octal. Neither is a validator, so for a page parameter I check the raw text with `/^[1-9]\d*$/`, then convert with `Number` and cap the value.

code

javascript · 11 lines
javascript
function parsePage(raw) {
  if (!/^[1-9]\d*$/.test(raw)) return null;
  const page = Number(raw);
  return page <= 10000 ? page : null;
}

console.log(parsePage('2'));    // 2
console.log(parsePage('2abc')); // null
console.log(parsePage('1e3'));  // null
console.log(parsePage(''));     // null
console.log(parsePage('0x10')); // null

go deeper

for a junior

Recall the plain cases: parseInt('12px') is 12 and Number('12px') is NaN. Pass 10 as the radix, and know that one function reads a prefix while the other needs the whole string.

for a middle

Predict the edges without running them: 1e3, the empty string, 0x10 with and without a radix, and 08. Explain that the default radix is inferred from a 0x prefix, and that a leading zero is not octal.

for a senior

Treat parsing as input validation. Trace a wrong page or a NaN offset back to the parser, then decide the accepted text and enforce it in one place, instead of trusting either converter.

for a principal

The team rule worth setting is one shared parser for each kind of external number, with a lint rule requiring a radix. It costs one small helper and removes many quiet per-call decisions.

## The symptom A list view reads its page from the URL with `parseInt(params.get('page'))`. Most requests are fine, but a crawler or a hand-edited link requests `?page=2abc` and gets page 2, `?page=1e3` gets page 1 rather than page 1000, and an empty `?page=` produces `NaN`, which then flows into the offset calculation. None of this raises an error, so nothing is logged. ## How parseInt reads a string `parseInt(string, radix)` is a **prefix parser**: 1. It converts the first argument to a string. 2. It skips leading whitespace and takes one optional `+` or `-`. 3. It settles the radix (see below). 4. It reads characters while they are valid numerals in that radix. 5. It stops at the first invalid character and **ignores it and everything after it**, returning what it has. If there was no valid first character, it returns `NaN`. That is why `e` ends the number in `1e3`, and why the `.` in `2.9` does too: neither is a numeral in base 10. Step 1 has its own trap. Because `parseInt` stringifies first, passing a number can go wrong: `1e21` becomes the string `'1e+21'`, and `0.0000005` becomes `'5e-7'`, so `parseInt` returns `1` and `5`. Use `Math.trunc` to truncate a number, and keep `parseInt` for text. ## How Number reads a string `Number(string)` is a **whole-string conversion**. It ignores surrounding whitespace and parses what remains as if it were a numeric literal. Anything left over makes the result `NaN`; there is no partial success. It understands forms `parseInt` does not, such as exponents, decimals, and the `0b` and `0o` prefixes. | Input | `parseInt(x)` | `Number(x)` | Why they differ | |---|---|---|---| | `'2abc'` | `2` | `NaN` | Prefix versus whole string | | `'1e3'` | `1` | `1000` | `e` is not a base-10 numeral | | `'2.9'` | `2` | `2.9` | `.` ends `parseInt`'s read | | `''` | `NaN` | `0` | The empty string converts to `0` | | `'.5'` | `NaN` | `0.5` | No valid first numeral for `parseInt` | | `'0b11'` | `0` | `3` | `parseInt` knows only the `0x` prefix | | `'0x10'` | `16` | `16` | Same result, by inference without a radix | | `' 42 '` | `42` | `42` | Both tolerate the whitespace | ## The radix When `radix` is missing, or converts to `0`, `NaN` or `Infinity`, `parseInt` infers it: - A string starting with `0x` or `0X`, after whitespace and sign, is read as base 16. - Anything else is read as base 10. So the default is **not** always 10. Current behaviour also does **not** treat a leading zero as octal: `parseInt('08')` is `8`. The old advice to pass a radix "because of octal" has outlived its reason, but the habit is still sound, because `parseInt('0x10')` is `16` while `parseInt('0x10', 10)` is `0`. An explicit radix states what you meant and stops user input from choosing the base. A nonzero radix outside the range 2 to 36 makes the result `NaN`. Inside the range, digits must fit, so `parseInt('2', 2)` is `NaN`, and `parseInt('12', 2)` is `1` since the read stops at `2`. ## Choosing for a real input Neither function validates. `Number` rejects `2abc`, but accepts `''`, `'1e3'`, `'0x10'` and `' 3 '`, none of which are page numbers you meant to allow. So: - Decide the accepted **text** first, and check the raw string against it, for example `/^[1-9]\d*$/`. - Convert with `Number` once the text is known to be digits. - Cap the value, since a long digit string can exceed the integer range a number holds exactly. - Return a clear rejection or a default in one place, rather than letting `NaN` or `0` reach the offset calculation. When leniency really is the goal, as with reading `12` from a CSS value like `12px`, `parseInt(value, 10)` is the right tool, and the partial parse is the feature. ## Finding it in production The bug leaves no error, so you have to go looking for it: - Log the raw parameter next to the parsed value, since the mismatch is then visible at once. - Follow any `NaN` to its source. An offset computed as `(page - 1) * size` becomes `NaN`, and whatever consumes it decides what the user sees. - Search for `parseInt` calls with no second argument, and for those fed by external text. - Test the awkward inputs directly: `''`, `'0'`, `'2abc'`, `'1e3'`, `'0x10'`, `' 3'`, and a very long digit string.

  • In JavaScript, why is `parseInt` a poor way to truncate a number, compared with `Math.trunc`?
    `parseInt` converts its argument to a string first, and very large or very small numbers stringify in exponential notation. `1e21` becomes `'1e+21'`, so `parseInt` returns `1`, and `0.0000005` becomes `'5e-7'`, so it returns `5`. It only appears to work on ordinary values. `Math.trunc` operates on the number itself and gives `1e21` and `0`.
  • In JavaScript, what does `parseInt` do with a radix of 0, 1 or 37?
    A radix of `0` counts as not provided, so the radix is inferred: 16 for a `0x` prefix, otherwise 10, and `parseInt('10', 0)` is `10`. A nonzero radix outside 2 to 36 always returns `NaN`, so `parseInt('10', 1)` and `parseInt('10', 37)` are both `NaN`. The radix never throws, which makes a wrong one easy to miss.
  • In JavaScript, why is `Number` alone not enough to validate a `?page=` value?
    It rejects trailing junk, but it accepts text that is not a page number: `Number('')` is `0`, `Number('1e3')` is `1000`, `Number('0x10')` is `16`, and `Number(' 3 ')` is `3`. A range check catches some of these and misses others. Checking the raw text against the exact form you accept, then converting, closes all of them.

  • parseInt('08') is 0 in current engines because a leading zero means octal.
  • parseInt throws an error when the string contains characters it cannot read.
  • parseInt without a radix always uses base 10.
  • parseInt('1e3') is 1000 because parseInt understands exponents.
  • Number stops at the first invalid character just as parseInt does.
  • Number('') is NaN because the string holds no digits.