Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript object property quotes [duplicate]

Let's say I have the following object:

var VariableName = {
    firstProperty: 1,
    secondProperty: 2
}

Do I have to wrap the object properties in quotes like this?

var VariableName = {
    'firstProperty': 1,
    'secondProperty': 2
}

Is this Single quotes in JavaScript object literal the correct answer?

like image 734
machineaddict Avatar asked Feb 08 '12 11:02

machineaddict


3 Answers

No, you don't need to do that.

The only reasons to quote object-keys are

  • the property name is reserved/used by the browser/js engine (eg. "class" in IE)
  • you have special characters or white spaces in your key

so for instance

var VariableName = {
    "some-prop": 42,  // needs quotation because of `-`
    "class": 'foobar' // doesn't syntatically require quotes, but it will fail on some IEs
    valid: 'yay' // no quotes required
};
like image 136
jAndy Avatar answered Sep 29 '22 07:09

jAndy


You only have to use the quotes around the property, if the property name is a reserved word (like for, in, function, ...). That way you prevent Javascript from trying to interpret the keyword as a part of the language and most probably get a syntax error. Furthermore, if you want to use spaces in property names, you also have to use quotes. If your property names are just normal names without any collusion potential or spaces, you may use the syntax you prefer.

One other possibility that requires quotes is the use of Javascript minifiers like google closure compiler, as it tends to replace all property names. If you put your property names in quotes, however, the closure compiler preserves the property as you coded it. This has some relevance when exporting objects in a library or using an parameter object.

like image 36
Sirko Avatar answered Sep 29 '22 08:09

Sirko


Property names in object literals must be strings, numbers or identifiers. If the name is a valid identifier, then you don't need quotes, otherwise they follow the same rules as strings.

firstProperty and secondProperty are both valid identifiers, so you don't need quotes.

See page 65 of the specification for more details.

like image 31
Quentin Avatar answered Sep 29 '22 09:09

Quentin