parseInt with a radix in JavaScript
Intermediate · 4 min read
Numbers don't always arrive written in ordinary decimal. A color code like ff8800 is written in hexadecimal. A permission flag might be stored as binary, like 101. A zero-padded time like 08:05 has a leading zero that once confused JavaScript. To turn any of these strings into a number, you use parseInt and tell it which number system the text is written in.
In this tutorial you will read binary, hex and decimal strings with parseInt, see what happens when a digit doesn't fit, and solve a famous puzzle: why ['10', '10', '10'].map(parseInt) doesn't give three tens. You need to know what a function and an array are, and have seen map once.
Number bases, in plain words
Everyday numbers use ten digits, 0 to 9. That is called base 10. Other bases use a different set of digits:
- Base 2 (binary) uses only 0 and 1.
101means one 4, no 2s and one 1, which is 5. - Base 16 (hexadecimal, or hex) uses 0 to 9 and then a to f, where
ais 10 andfis 15.ffmeans fifteen 16s plus 15, which is 255.
The base is also called the radix. parseInt takes it as its second argument, and it can be any whole number from 2 to 36. Base 36 uses all ten digits and all 26 letters.
console.log(parseInt('z', 36)); // 35: z is the last digit in base 36
How parseInt reads a string
parseInt reads from the left, one character at a time. As long as each character is a valid digit for the base, it keeps going. At the first character that isn't, it stops and returns what it has so far. If even the first character is not a digit, it returns NaN, which means "Not a Number".
Here is the exercise. Try it on your own first if you like, then read on and we will build it together.
21 parseInt and the radix
fairRead '101' as binary, 'ff' as hex and '08' as decimal. Then explain why ['10', '10', '10'].map(parseInt) does not give three tens.
Stuck? Three hints, smallest first
- 1.
parseInttakes a second argument: the base, from 2 to 36. - 2. Without it, only a
0xprefix changes the base; a leading zero no longer means octal. - 3.
mappasses the index as the second argument, andparseIntreads that as the radix.
Step 1: binary and hex
Pass the base as the second argument:
console.log(parseInt('101', 2)); // 5
console.log(parseInt('ff', 16)); // 255
The same text means different numbers in different bases. '101' in base 10 is one hundred and one, but in base 2 it is 5. That is why the radix matters: it changes the answer.
Step 2: what happens with no radix
If you leave the radix out, parseInt makes a guess. It only looks for one thing: a 0x at the start, which is how JavaScript marks a hex number.
console.log(parseInt('0x1f')); // 31: the 0x prefix means hex
console.log(parseInt('0xff', 16)); // 255: 0x is allowed with radix 16 too
console.log(parseInt('08')); // 8: a leading zero is just decimal
The '08' line is the historical trap. Older engines treated a leading zero as base 8 (octal), so parseInt('08') used to come out as 0. That broke code reading zero-padded dates and times. Modern engines read it as decimal 8, but passing the radix means nobody has to remember the history.
Step 3: digits that don't fit the base
Base 8 only has the digits 0 to 7. Watch what parseInt does with an 8 or a 9:
console.log(parseInt('8', 8)); // NaN: 8 is not a base-8 digit
console.log(parseInt('129', 8)); // 10: reads '12', stops at the 9
In the first line, the very first character is invalid, so there is nothing to return but NaN. In the second, parseInt reads 1 and 2, hits 9, and stops. '12' in base 8 is one 8 plus 2, which is 10. No error is thrown, so a wrong digit can slip through quietly.
The radix itself must be between 2 and 36. Anything outside that range gives NaN:
console.log(parseInt('1', 1)); // NaN
console.log(parseInt('1', 37)); // NaN
Step 4: the map puzzle
Now the famous one. You might expect this to turn three strings into three numbers:
const mapped = ['10', '10', '10'].map(parseInt);
console.log(mapped); // [ 10, NaN, 2 ]
The reason is how map calls your function. It doesn't pass just the item. It passes three things: the item, its index (position) and the whole array. parseInt takes the index as its radix. So the three calls are really:
console.log(parseInt('10', 0)); // 10: radix 0 means "use the default"
console.log(parseInt('10', 1)); // NaN: radix 1 is out of range
console.log(parseInt('10', 2)); // 2: '10' in binary is 2
Nothing is broken. parseInt is doing exactly what it is told, with arguments you didn't mean to give it.
Step 5: the fix
Wrap the call in a small arrow function, so you decide which arguments parseInt gets:
console.log(['10', '10', '10'].map((s) => parseInt(s, 10))); // [ 10, 10, 10 ]
console.log(['10', '10', '10'].map(Number)); // [ 10, 10, 10 ]
Number takes only one argument, so the extra index and array that map passes are ignored. Both lines give three tens.
The full solution
The answer panel reads each string in the exercise, prints the no-radix and bad-digit cases, and shows the map(parseInt) result. The checks underneath confirm each value, including that the second mapped call is NaN and the third is read as binary. Press Run to see the output.
const mapped = ['10', '10', '10'].map(parseInt); // radix 0, then 1, then 2
console.log("parseInt('101', 2) :", parseInt('101', 2));
console.log("parseInt('ff', 16) :", parseInt('ff', 16));
console.log("parseInt('0x1f') :", parseInt('0x1f'), '<- prefix honoured with no radix');
console.log("parseInt('08') :", parseInt('08'), '<- decimal, not octal');
console.log("parseInt('8', 8) :", parseInt('8', 8), '<- 8 is not a base-8 digit');
console.log("parseInt('129', 8) :", parseInt('129', 8), "<- read '12', stopped at the 9");
console.log('map(parseInt) :', mapped);
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('binary needs radix 2', parseInt('101', 2), 5);
test('hex needs radix 16, or a 0x prefix', [parseInt('ff', 16), parseInt('0xff', 16)], [255, 255]);
test('a 0x prefix is honoured even with no radix given', parseInt('0x1f'), 31);
test('a leading zero is decimal in modern engines', parseInt('08'), 8);
test('8 is not a base-8 digit, so that parse gives NaN', Number.isNaN(parseInt('8', 8)), true);
test('a digit beyond the radix stops the scan', parseInt('129', 8), 10);
test('radix 1 and radix 37 are out of range', [Number.isNaN(parseInt('1', 1)), Number.isNaN(parseInt('1', 37))], [true, true]);
test('map hands parseInt the index, so the second call gets radix 1', mapped.map(Number.isNaN), [false, true, false]);
test('and the third is read as binary', mapped[2], 2);
Always pass the radix. The historical reason was octal — parseInt('08') used to be 0 in some engines, which broke every zero-padded date and time string ever written. Modern engines default to 10, but the habit costs one argument and removes the question.
['10','10','10'].map(parseInt) is the classic interview answer: map calls its function with (value, index, array), so the calls are parseInt('10', 0), parseInt('10', 1) and parseInt('10', 2). Radix 0 means "use the default", radix 1 is invalid, radix 2 reads binary. Write xs.map((s) => parseInt(s, 10)) or xs.map(Number).
Common mistakes
- Leaving out the radix. It works for most decimal input today, but the reader has to know the rules to be sure. Write
parseInt(s, 10). - Passing
parseIntstraight tomap. The index becomes the radix. Use(s) => parseInt(s, 10)orNumber. - Trusting
parseIntto reject bad digits.parseInt('129', 8)quietly gives 10. If every character must be valid, check the string first or compare your result against the full input.
Try it yourself
- Read the hex color parts
'ff','88'and'00'with radix 16. You should get 255, 136 and 0. - Predict
parseInt('2024-12-05', 10), then run it. Where does it stop, and why? - Write
fromBinary(s)that returnsnullinstead of a number ifscontains anything except 0 and 1.