Did you know that JavaScript's parseInt
function to convert strings to integers has an optional second argument to explicitly define a radix
? It specifies the base of the number you're going to parse. New JavaScript developers often assume that not specifying a base means it will use the most common one: base 10. This is not always true! Most JavaScript runtimes will attempt to guess the radix based on the start of the value. If the number begins with a 0
, it will parse as octal (radix of 8). If the number starts with 0x
, it will parse as hexadecimal (radix of 16).
That's why it's very important that our code always specify a radix.
Try it out: parseInt("09");
or parseInt("010");