Search code examples
javascriptjavascript-objectsoctal

Confused about javascript object keys


If I define a new Object in javascript, with var myobject = {} I will have an empty object, as expected. However, I fail to understand the logic behind this. Note that it all works, but I don't get it, more a tease than anything else:

var myobject = {};                 // Object{}
    myobject[001] = "001";         // Object {1: "001"}, So 001 turns to 1
    myobject[0099999] = "0099999"; // Object {1: "001", 99999: "0099999"}
    //Last line only makes sense after this one (shortened version)▼
    myobject[0023122] = "0023122"  // Object {... 9810: "0023122" ...}

I know I can't access those properties with myobject.0023122 since they start with a digit, but I can't by doing this myobject['0023122'] either so I'm assuming that the number 0023122 is transformed to the property with a key 9810 since I can do myobject['9810'] and get the result.

What's fascinating about this is that I can do myobject[99999] and myobject['99999'] so javascript didn't need to reject my key although I lose my leading zeros. I'm not talking about what's wrong and right to do, just what is the reason for the number 0023122 to be converted to 9810 while even 0023123 converts gracefully to 23123 just as 0099999 converts to 99999

  • I assumed it was too big of a number, that's why I tried with one even bigger.
  • If you remove the leading zeros, the key becomes "23123"

Solution

  • Javascript supports octal numbers:

    Positive octal numbers must begin with 0 (zero) followed by octal digit(s).

    0023122 (in octal) is 9810 (in decimal)

    So any number that has all digits less than 8, but starts with a 0, will be converted to octal.

    If it has an 8 or 9, it will get truncated if it starts with a 0.

    091 -> 91

    but

    071 -> 57

    Of course, if you use string keys, nothing to worry about:

     myobject["001111"] = "001111"
     myobject[001111] = 585