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?
First answer
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).
Second answer
There is no difference here. Just a matter of style. One of the reasons for doing this is being able to use ‘super’ or ‘class’ as a key since those are reserved keywords.
Some people might be tempted to pass in a string with whitespace then call o[‘I can have whitespace’] But I would call that bad practice.
Third answer
No, not to javascript. However, some JSON parsers will fail when the quotes around the keys are not present.