Object Key Syntax: Quotes vs. No Quotes
In JavaScript, objects can be created using key-value pairs. However, the use of quotes around object keys has sparked questions about potential differences.
Do Quotes Matter?
The answer is: no. The presence or absence of quotes does not influence the object's functionality or behavior. Both the following code snippets define identical objects:
obj = {foo: 'bar'}; obj = {'foo': 'bar'};
Exception: Identifier Validation
The sole exception arises when using keys that are not valid JavaScript identifiers. In this case, quotes become necessary to prevent syntax errors. For instance, the following key requires quotes:
obj = {'-foo': 'bar'}; // Key must be quoted because it contains a '-'
JSON Requirement
It's worth noting that the JSON data format strictly requires double quotes around keys. While not essential for JavaScript objects, using quotes ensures compatibility, especially when exchanging data with JSON.
The above is the detailed content of JavaScript Object Keys: To Quote or Not to Quote?. For more information, please follow other related articles on the PHP Chinese website!