Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rules for unquoted JavaScript Object Literal Keys?

Tags:

javascript

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.

like image 896
jterrace Avatar asked Feb 20 '12 19:02

jterrace


People also ask

Do object keys need quotes?

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.

What is the correct syntax for declaring an object literal?

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.

What are JavaScript object literals?

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.

Should JavaScript object keys be strings?

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.


1 Answers

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.

Screenshot

like image 134
Mathias Bynens Avatar answered Sep 16 '22 11:09

Mathias Bynens