Why Does Parseint(1/0, 19) Return 18?

Why does parseInt(1/0, 19) return 18?

If you’ve ever come across the expression parseInt(1/0, 19) in JavaScript and wondered why it returns 18 instead of NaN (Not a Number), you’re not alone. This behavior can be quite confusing, but there is a logical explanation behind it.

The parseInt() function in JavaScript is used to parse a string and convert it into an integer. It takes two parameters: the string to be parsed and the radix, which specifies the base of the number system to be used for parsing.

In this case, the string being parsed is 1/0 and the radix is 19. The string 1/0 is not a valid number in base 19, as division by zero is undefined in mathematics. However, JavaScript tries to parse it as a number using the given radix.

When parsing a string with a radix, JavaScript looks for the first characters that are valid in the given base and stops parsing when it encounters an invalid character. In this case, the first character 1 is valid in base 19, but the forward slash / is not.

As a result, JavaScript stops parsing at the forward slash and returns the parsed integer value, which is 18. It ignores the invalid character and any subsequent characters in the string.

Here’s the code snippet that demonstrates this behavior:

const result = parseInt("1/0", 19);
console.log(result); // Output: 18

As you can see, the output is indeed 18.

It’s important to note that this behavior is specific to the parseInt() function when a radix is provided. If you omit the radix or use a radix of 10 (the default), the expression parseInt(1/0) will correctly return NaN.

To avoid confusion and ensure consistent results, it’s generally recommended to use the radix of 10 when using parseInt() unless you have a specific need for a different base.

So, the next time you encounter the expression parseInt(1/0, 19) and wonder why it returns 18, you’ll know the reason behind it.


Posted

in

, ,

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *