Rules for unquoted JavaScript Object Literal Keys?
Solution 1:
From Unquoted property names / object keys in JavaScript, my write-up on the subject:
Quotes can only be omitted if the property name is a numeric literal or a valid identifier name.
[…]
Bracket notation can safely be used for all property names.
[…]
Dot notation can only be used when the property name is a valid identifier name.
-1
is not a numeric literal, it’s a unary -
operator followed by a numeric literal (1
).
I also made a tool that will tell you if any given property name can be used without quotes and/or with dot notation. Try it at mothereff.in/js-properties.
Solution 2:
Interesting question.
The thing is, there's no difference between typing
var d = {24: 'foo'};
and
var d = {"24": 'foo'};
You can verify this by doing:
var d = {24:'foo', "24":'bar'};
Notice that it only has one "24" property (and fails in strict mode).
So while this doesn't explain why you can't do -1 without quotes, hopefully it does explain that "-1" is just as good.
Interestingly, unquoted fractional numbers seem to work fine.
Edit: Felix Kling explains why it doesn't work in a comment on another answer. -1
isn't a numeric literal, it's an expression with a numeric literal and a unary -
operator -- therefore it's not suitable as an object key.
Solution 3:
Its because -1
isn't a valid variable identifier.