10

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!

3
  • thats javascript for ya. I think you shold get an error for not having ; at the end of your var statements Commented Feb 15, 2011 at 16:08
  • @Matt: Nope, JavaScript has some pretty sophisticated automatic semicolon insertion; only, please don't rely on it, things can go horribly wrong when you omit semicolons in critical places. Commented Feb 15, 2011 at 20:50
  • @Marcel Korpel Exactly, I meant in my opinion it should not be automatic and should throw a syntax error when you forget them. Commented Feb 16, 2011 at 9:00

3 Answers 3

19

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.

Sign up to request clarification or add additional context in comments.

Comments

8

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

Comments

0

123 is not, per-se, an invalid property name. Any property name that is not a string is typecast to a string with the toString method.

1 Comment

Nope; see Felix' answer to know what's wrong. You can only use 123a as a PropertyName when you enclose that property name within quote characters; moreover, you can only access such a property using the square bracket notation (object["123a"]).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.