Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A question about JavaScript object property name

Tags:

javascript

I've a question about JavaScript object property name. Check out codes below:

<!DOCTYPE html>
<meta charset="UTF-8">
<title>An HTML5 document</title>
<script>
    var obj = {
        123: 'go' // 123 is not a valid JavaScript name. No error here.
    };
    var obj2 = {
        123a: 'go' // An Error occurred.
    };
</script>

If a JavaScript object's property name is a valid JavaScript identifier, object porperty name's quotes are not necessary.

E.g.

({go_go: 'go'}); // OK
({go-go: 'go'}); // Fail

In the codes above, 123a is an invalid JavaScript name and it's not be quoted. So An error occurred. But 123 is also an invalid JavaScript name and also it's not quoted, why no error here? Personally I think 123 must be quoted.

Thank you!

like image 739
weilou Avatar asked Feb 15 '11 16:02

weilou


2 Answers

Have a look at the specification:

ObjectLiteral :
    { }
    { PropertyNameAndValueList }
    { PropertyNameAndValueList  ,}

PropertyNameAndValueList :
    PropertyAssignment
    PropertyNameAndValueList , PropertyAssignment

PropertyAssignment :
    PropertyName : AssignmentExpression
    get PropertyName ( ){ FunctionBody }
    set PropertyName ( PropertySetParameterList ){ FunctionBody }

PropertyName :  
    IdentifierName
    StringLiteral
    NumericLiteral

So a property name can be either an identifier name, a string or a number. 123 is a number whereas 123a is neither of those above.

like image 55
Felix Kling Avatar answered Sep 28 '22 03:09

Felix Kling


The key portion of each key-value pair can be written as any valid JavaScript identifier, a string (wrapped in quotes) or a number:

var x = {
    validIdentifier: 123,
    'some string': 456,
    99999: 789
};

See the spec: http://bclary.com/2004/11/07/#a-11.1.5

like image 35
James Avatar answered Sep 28 '22 03:09

James