Home >Web Front-end >JS Tutorial >Quoted vs. Unquoted Object Keys in JavaScript: What's the Semantic Difference?

Quoted vs. Unquoted Object Keys in JavaScript: What's the Semantic Difference?

Patricia Arquette
Patricia ArquetteOriginal
2025-01-04 08:35:34904browse

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

  • With quotes: When the key is enclosed in quotes (both single or double), it becomes a string. This means that property access with dot notation (e.g., obj.foo) and bracket notation (e.g., obj["foo"]) will behave identically.
  • Without quotes: If the key is not enclosed in quotes, it becomes an identifier. This means that property access with dot notation works only for valid JavaScript identifiers. If the key contains characters that are not allowed in identifiers (e.g., "-", "&", "%"), bracket notation must be used.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn