In JavaScript, you can define an object like this:
var d = {1: 'test'};
and I can set a key with a negative number index like this:
d[-1] = 'test2';
but if I try to use a negative number in the literal initialization, I get an error:
var d = {1: 'test', -1: 'test2'};
Uncaught SyntaxError: Unexpected token -
Why is this? Why can’t I use a literal negative number as a key to an object? Is there a workaround that allows me to initialize it as a literal. I know I could use strings instead, but I want to use integers.
From Unquoted property names / object keys in JavaScript, my write-up on the subject:
-1is 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.