0

I am working with an array of numbers

let nums = [02000, 02000, 02200, 02020,02002]


The problem is when I console.log(nums) it prints out [1024,1024,1152,1040,1026].

Why is it changing my numbers?

nagnag
  • 47
  • 1
  • 1
  • 7
  • 4
    Your "numbers" have a leading zero. JavaScript interprets these to be octal numbers, not decimal. https://decimaltobinary.pro/_octal__2000_in_decimal_ – duffymo May 11 '22 at 18:56
  • it isn't. [Those are the same numbers as per the language specification](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Numbers_and_dates#numbers). Just like how `16`, `0b10000`, `020`, `0xF`, and `0.16e2` are all the exact same number. Just written as decimal, binary, octal, hexadecimal, and scientific numbers respectively. – Mike 'Pomax' Kamermans May 11 '22 at 18:57
  • Extended answer here https://stackoverflow.com/questions/6505033/number-with-leading-zero-in-javascript/28354557#28354557 – Grumpy May 11 '22 at 19:03

1 Answers1

1

In JavaScript, Numeric Literals have their own lexical grammar.

When numbers start with a leading 0, it may be interpreted as an octal.

Note that decimal literals can start with a zero (0) followed by another decimal digit, but if all digits after the leading 0 are smaller than 8, the number is interpreted as an octal number.

romellem
  • 5,792
  • 1
  • 32
  • 64