Object Key Syntax with and Without Quotes
Question:
Does the presence or absence of quotes around object keys have any ramifications?
And:
obj = {'foo': 'bar'} <br>
obj = {foo: 'bar'}<br>
Which one is preferred and why?
Answer:
No, there is no fundamental difference between object keys declared with or without quotes.
Explanation:
Object keys can be defined without quotes if they adhere to valid JavaScript identifier syntax. Reserved keywords or symbols require enclosing them in quotes to be recognized as keys.
However, the JSON (JavaScript Object Notation) data exchange format mandates double quotes around keys, rendering the key syntax without quotes invalid in this context.
Therefore, for interoperability with JSON, using double quotes around keys is recommended, especially in scenarios where the data may be exchanged with other applications or services.
The above is the detailed content of To Quote or Not to Quote: When Are Quotes Necessary for JavaScript Object Keys?. For more information, please follow other related articles on the PHP Chinese website!