ali.j
ali.j

Reputation: 11

array store a different number than input

I just stated learning JS and I was trying a very simple code when I got a strange result which I cannot explain why it happened. I tried to define a very simple array like below:

var a=['hello',0,"2313dog!"," ",45.78,-021,-657]

But once it’s executed in Chrome console the element -021 was changed to -17 , like:

["hello", 0, "2313dog!", " ", 45.78, -17, -657]

I know -021 is not a number, and I can add it as a tring, but I don't now why and how it changed to -17. Can someone please explain what happened and if there is a name for this. Thanks!

Upvotes: 1

Views: 58

Answers (1)

Mark
Mark

Reputation: 989

A number prefixed by a 0 is interpreted as an octal (base-8) number in javascript and other languages. So 2 * 8 + 1 = 17.

Similarly, a number prefixed by 0x is interpreted as hexadecimal (base-16), so 0x11 would also be converted to 17.

Upvotes: 3

Related Questions