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!
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With