KWallace
KWallace

Reputation: 1700

Understanding implicit conversion in Javascript

I hunted down a bothersome JavaScript error where I was passing one argument, but when it was received, it was something completely different. I fixed it, but would like to know what was happening for future reference.

What I should have passed as an argument is '0616' (with quotes). What I actually passed was 0616 (without the quotes).

So, when it was received, some kind of implicit numeric conversion took place, and it was received as 398. I understand implicit and explicit conversion, but WHAT was happening to turn 0616 into 398. The leading zero seems to have something to do with it because other values that I passed that were non-zero in the most significant digit survived just fine. It's only those that begin with zero?

But what relation is there between 398 and '0616' ?

Any ideas?

Upvotes: 3

Views: 153

Answers (3)

Michael Voznesensky
Michael Voznesensky

Reputation: 1618

Ahh the magical world of javascript!!

Any numeric literal that starts with a 0 is treated as an octal number.

A hacky workaround is

parseInt('0616', 10)

Upvotes: 5

Leo
Leo

Reputation: 13848

0616 is the old octal number format. In new spec it should be 0o616, however the old format is still supported by browsers.

See this wiki page:

prefix 0o was introduced to .... and it is intended to be supported by ECMAScript 6 (the prefix 0 has been discouraged in ECMAScript 3 and dropped in ECMAScript 5).

Upvotes: 3

alzclarke
alzclarke

Reputation: 1765

the reason is that the leading zero is javascript notation for base octal, e.g. 010 = 8. The notation for hexadecimal is a leading 0x, e.g. 0x10 = 16

Upvotes: 2

Related Questions