Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any functional difference between using and not using quotes with javascript property name assignments? [duplicate]

I'm not sure of the exact wording to use, but I have seen object assignments in javascript done two wasy

$('#test').dataTable({ fnInitComplete: myFunction });

and

$('#test').dataTable({ "fnInitComplete": myFunction });

Is there any actual difference between these, or any gotchas to be aware of?

like image 969
KallDrexx Avatar asked Nov 02 '11 19:11

KallDrexx


3 Answers

The currently accepted answer is incorrect:

However, if the key is not a valid identifier (eg, it's a keyword, or it has spaces or punctuation), quotes are required.

The quotes aren’t required if you use a numeric literal as a property name. Also, keywords and reserved words are valid identifier names, and all identifier names (not just identifiers) are valid JavaScript property names.

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.

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 41
Mathias Bynens Avatar answered Nov 11 '22 08:11

Mathias Bynens


There is no difference.

However, if the key is not a valid identifier (eg, it's a keyword, or it has spaces or punctuation), quotes are required.

Also, the JSON standard (which is not Javascript) always requires double-quotes.

like image 161
SLaks Avatar answered Nov 11 '22 09:11

SLaks


The main difference is that with quotes, you can use keys with spaces, js keywords, etc that are illegal as normal symbols. That's why JSON requires them.

like image 1
rob Avatar answered Nov 11 '22 07:11

rob