Home >Web Front-end >JS Tutorial >Quoted vs. Unquoted Object Keys in JavaScript: What's the Semantic Difference?
Quotes in Object Keys: A Difference in Semantics?
In JavaScript, object properties can be defined using keys with or without quotes. While this may seem like a minor difference, it does introduce a subtle change in the behavior of the property access.
Properties with Quotes vs. Without Quotes
Example
Consider the following example:
obj1 = {'foo': 'bar'}; obj2 = {foo: 'bar'};
In this case, both obj1 and obj2 have the same key-value pair, but the property can be accessed differently:
console.log(obj1.foo); // 'bar' console.log(obj2.foo); // ReferenceError: foo is not defined console.log(obj2['foo']); // 'bar'
As you can see, obj2 cannot be accessed using dot notation because the key "foo" is not a valid JavaScript identifier. Instead, bracket notation must be used.
Note:
While there is no significant difference in functionality between using quotes or not, the JSON data exchange format requires double quotes around property keys. If you plan on exchanging data in JSON format, it is recommended to always use quotes around object keys.
The above is the detailed content of Quoted vs. Unquoted Object Keys in JavaScript: What's the Semantic Difference?. For more information, please follow other related articles on the PHP Chinese website!