Devid Farinelli Devid Farinelli - 1 year ago 116
Javascript Question

Javascript: why parseInt(8,3) == NaN and parseInt(16,3) == 1?

I'm reading this but I'm confused by what is written in the parseInt with a radix argument chapter

enter image description here


parseInt(8, 3) -> NaN
parseInt(16, 3) -> 1

AFAIK 8 and 16 are not Base3 numbers, so
parseInt(16, 3)
should return

enter image description here

Answer Source

This is something people trip over all the time, even when they know about it. :-) You're seeing this for the same reason parseInt("1abc") returns 1: parseInt stops at the first invalid character and returns whatever it has at that point. If there are no valid characters to parse, it returns NaN.

parseInt(3, 3) means "parse "3" in base 3" (note that it converts the number 3 to a string; details in the spec). But in base 3, the single-digit numbers are just 0, 1, and 2. It's like asking it to parse "9" in octal. Since there were no valid characters, you got NaN.

parseInt(16, 3) is asking it to parse "16" in base 3. Since it can parse the 1, it does, and then it stops at the 6 because it can't parse it. So it returns 1.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download