Object Keys with and Without Quotes: A Difference in Appearance
While working with JavaScript objects, you may encounter object keys with or without quotes. It's a common question whether there's any difference between:
obj = {'foo': 'bar'}; // With quotes
and
obj = {foo: 'bar'}; // Without quotes
The Answer: No Significant Difference
In most cases, there is no significant difference between keys with and without quotes. JavaScript allows unquoted keys as long as they are valid JavaScript identifiers.
Exceptions: Using Special Characters in Keys
However, if you need to use special characters in your keys, such as dashes (-), you must use quotes.
JSON Requirement
It's important to note that the JSON data exchange format requires double quotes around keys. While this doesn't affect the functionality of JavaScript objects, it's a consideration if you plan to exchange data with a system that uses JSON.
Example
Let's consider the following code:
var obj1 = {'foo': 'bar', 'baz-1': 'qux'}; var obj2 = {foo: 'bar', 'baz-1': 'qux'};
Both obj1 and obj2 will create objects with the same keys and values. However, if you try to convert obj1 to a JSON string, you'll encounter an error due to the unquoted key with a dash.
In conclusion, while there's typically no functional difference between keys with and without quotes, it's recommended to use quotes for keys that include special characters or when dealing with JSON data exchange.
The above is the detailed content of Do Quoted and Unquoted Object Keys in JavaScript Make a Difference?. For more information, please follow other related articles on the PHP Chinese website!