What is the Purpose of the Second Param in parseInt?
It is often overlooked or an unknown part of parseInt
, but we have a second parameter that is responsible for the radix: The numeral system to be used. It can be an integer between 2 and 36. It is always a good practice to define the radix when using parseInt
. Take the following as an example:
Copied to clipboard! Playground
// This will return NaN
parseInt(2, 2);
// This will return 2
parseInt(2, 10);
If you simply want to convert a string into a number, you can also use the Number
function more reliably, which doesn't require a radix:
Copied to clipboard!
Number('2'); // returns 2
Number(2); // returns 2
Number('a'); // returns NaN
When the function is used on an invalid number, it will return NaN
.
Resources:
π More Webtips
Master the Art of Frontend
- Access 100+ interactive lessons
- Unlimited access to hundreds of tutorials
- Prepare for technical interviews