var foo = { "bar": 123 };
var foo = { bar: 123 };
The above two lines of JavaScript are exactly equivalent. In either case you can access the "bar"
property in two different ways:
console.log( foo.bar ); # => 123
console.log( foo["bar"] ); # => 123
You only need to use the quotation mark syntax ({ "bar": 123 }
) when the key isn't a valid JavaScript identifier. To quote MDN:
A JavaScript identifier must start with a letter, underscore (_), or dollar sign ($); subsequent characters can also be digits (0-9). Because JavaScript is case sensitive, letters include the characters "A" through "Z" (uppercase) and the characters "a" through "z" (lowercase).
Starting with JavaScript 1.5, you can use ISO 8859-1 or Unicode letters such as å and ü in identifiers. You can also use the \uXXXX Unicode escape sequences as characters in identifiers.
For example, this is valid:
var obj = { "": 1,
"!": 2,
"foo bar": 3,
"99bottles": 4 }
But without the quotation marks, any of those would throw an error.
There's one other time when quotation marks are necessary, and that's when you want to use a key that's a reserved word in JavaScript, like return
or else
or class
. Sometimes you can do it just fine:
var obj = { else: 123 }
console.log( obj.else ) # => 123
...but this depends on the JavaScript parser being able to tell that you're using it as a property name and not as a keyword. If, for example, you open up your JavaScript console right now and type:
{ else: 123 }
...you'll get a SyntaxError. So, when it comes to words that have special meaning in JavaScript (there's a full list here), it's best to use quotation marks:
var obj = { "else": 123 }
On the other side of the coin—which is to say, getting things out of the object you've created—the story is much the same. Suppose we have this object:
var obj = { foo: 1, // note that we can mix quoted and non-quoted if we want
"": 2,
"99bottles": 3,
"else": 4,
"foo bar": 5,
$gt: 6 }
For keys that are valid identifiers, we can use regular "dot notation" to access the properties, but for the others we have to use "bracket notation":
obj.foo # => 1
obj[""] # => 2
obj.99bottles # => SyntaxError: Unexpected token ILLEGAL
obj["99bottles"] # => 3
obj.else # => 4
obj["foo bar"] # => 5
obj.$gt # => 6
Finally, it's worth noting that JSON is a subset of JavaScript. This is valid JavaScript, but it's not a valid JSON object:
{ foo: "bar" }
Quotation marks are required around JSON property names. The below is valid JSON:
{ "foo": "bar" }