Search code examples
javascriptdictionaryprogramming-languageslanguage-designidentifier

Why can't JavaScript dictionary keys start with a number using the myDict.123 syntax?


Preface

The answer to this question may very well be "because the creators of JavaScript decided so." Mostly I'm just curious if there's a specific reasoning behind this decision, aside from mere consistency with other identifiers/variable names and other languages.

Question

This is legal:

var foo = { "1abc": "bar", 1: "lol" };
document.write(foo["1abc"]);
document.write(foo[1]);

Lines 2-3 of this are not legal:

var foo = { "1abc": "bar", 1: "lol" };
document.write(foo.1abc);
document.write(foo.1);

I have not used a language where identifiers can start with a number, but until JavaScript, I also have not used a language where dictionary values could be referenced using both dict[index] and dict.index syntax.

I'm not sure if dictionary keys are considered identifiers or not. If they are, then this question is a no-brainer.

Then again, I'm not really clear why JavaScript identifiers can't start with a number, given that numbers are a Number type. In other languages (e.g. C#) numbers have types like int, long, double, etc causing 5L or 5D to specify "5 as long" and "5 as double" respectively. So, in theory, JavaScript identifiers could start with a number, and be fine (I think).

C#:

var x = 5L; // x is long type
var y = 5D; // x is double type

JavaScript:

var x = 5L; // syntax error
var y = 5D; // syntax error

So, my guess is that JavaScript identifiers can't start with a number for consistency with other languages, and JavaScript dictionary keys can't be referenced with dict.123 syntax for consistency with other JavaScript identifiers. Is this the only reason?


Solution

  • I think you answered your own question. "because the creators of JavaScript decided so."

    From msdn: https://msdn.microsoft.com/en-us/library/ie/67defydd%28v=vs.94%29.aspx

    Lastly, what you are dealing with are object literals, not dictionaries. Javascript has two ways of retrieving member properties for different occasions. "." syntax is for static access, "[]" is for dynamic access. Consider the following:

    var myObj = {
      x:"foo",
      getX: function() {return this.x;}
    };
    
    var get = "get";
    var X = "X";
    alert(myObj[get+X]());  //Alerts "foo";
    

    Javascript lets you do some pretty dynamic things, that usually result in horribly unmaintainable code, but its still pretty cool.