1

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!

3
  • 3
    A number prefixed by a '0' is interpreted as an octal (base-8) number in javascript and other languages. So 2 * 8 + 1 = 17 Commented Jul 18, 2019 at 1:27
  • @Mark You should post as an answer Commented Jul 18, 2019 at 1:31
  • Hey thanks man! Sometimes I see people getting flack for posting trivial answers, but if you say so... Commented Jul 18, 2019 at 1:36

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.