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.
Unless an object key is a numeric literal or a valid identifier name, you need to quote it to avoid a syntax error from being thrown.
Declaring methods and properties using Object Literal syntax The Object literal notation is basically an array of key:value pairs, with a colon separating the keys and values, and a comma after every key:value pair, except for the last, just like a regular array.
Object Literal. In plain English, an object literal is a comma-separated list of name-value pairs inside of curly braces. Those values can be properties and functions.
JavaScript Objects are Associative Arrays whose Keys are Always Strings. Every object in JavaScript is an associative array whose keys are strings. This is an important difference from other programming languages, such as Java, where a type such as java.
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.
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