What is the difference between object keys with quotes and without quotes?

Is there any difference between

obj = {'foo': 'bar'} 

and

obj = {foo: 'bar'}

I have noticed that you can't use - in the key when I don't use the quotes. But does it actually make a difference? If yes, which?


Solution 1:

No, the quotes do not make a difference (unless, as you noted, you want to use a key that’s not a valid JavaScript identifier).

As a side note, the JSON data exchange format does require double quotes around identifiers (and does not allow single quotes).

Solution 2:

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.

Note that reserved words are allowed to be used as unquoted property names in ES5. However, for backwards compatibility with ES3, I’d suggest quoting them anyway.

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