Search code examples
javascriptobjectliteralsstring-literals

Property names in JavaScript


I have a question that has been really bugging me for quite a while and I cannot seem to find any resources that cover the topic. How can property names in JavaScript be string literals or numeric literals?

var obj = {
    "bar": "foobar",
    "foo": function() { return bar; }
}

This topic has bugged me ever since I learned about it a few years ago. I don't know where to get more in-depth information or what this is even called. I not confused on how this is set up as I know that a new object is being creating with members, bar & foo and then its assigned to the obj variable.

You cannot create a variable like var "bar" = "foobar"; because you'll get a syntax error. How is it valid for object literals? Any help on this would be very much appreciated.


Solution

  • In JavaScript, property names are String values - any String values. That's just how the language is specified.

    The relevant production:

    PropertyName :  
        IdentifierName
        StringLiteral
        NumericLiteral
    

    If an identifier, or a numeric literal is supplied, it is converted to a string value (SV).

    See: http://ecma-international.org/ecma-262/5.1/#sec-11.1.5

    So, for example:

    var obj = {
        foo: true, // the name of this property becomes 'foo'
        'bar': true, // the name of this property becomes 'bar'
        123: true // the name of this property becomes '123'
    };
    

    You can even use the empty string as a property name:

    var obj = {
        '': 'foo'
    };
    
    obj[''] // 'foo'