Devid Farinelli - 1 month ago 4x
Javascript Question

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

Why

`parseInt(8, 3) -> NaN`
and
`parseInt(16, 3) -> 1`
?

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

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.