JS: Property Dot Notation vs Bracket Notation
Dot Notation and Bracket Notation are two different ways to access property.
Dot Notation
object.key
-
Dot notation. Most convenient.
- Dot notation cannot be used when the property name contains space. e.g.
{"a b":7}
- Dot notation cannot be used when the property name is a language keyword or reserved word. e.g.
obj.for
. - Dot notation cannot be used when the property name is number-like. e.g.
obj.7
- Dot notation cannot be used to create new property at run time. For example, when you have a property name as value of a variable, constructed from user input.
- Dot notation cannot be used for Symbol key properties.
- Dot notation cannot be used when the property name contains space. e.g.
Bracket Notation
object[key]
- Bracket notation. Useful if key contains space or is a number or Symbol type, or is a variable.
object?.key
- Same as dot notation, but return undefined instead of error out if object is undefined or null γsee Optional Chaining Operatorγ
Example: Property Name with Space in It
// property name that contains space const x = { "a b": 8 }; console.log(x["a b"] === 8);
the following are syntax errors x[a b] SyntaxError: Unexpected identifier x."a b" SyntaxError: Unexpected string
Example: Property Name of Digits
// a property with name that's a digit const x = { "3": 8 }; console.log(x["3"] === 8); console.log(x[3] === 8); // JavaScript automatically convert 3 to string
following are syntax errors dot notation cannot be used x."3" SyntaxError: Unexpected string x.3 SyntaxError: Unexpected number
Example: creating property with a name from the value of a variable
Here is a example of creating property with a name from the value of a variable.
// creating a property, with name from a value of variable // dot notation won't work const jj = { "p1": 1 }; const v = "p2"; jj[v] = 2; console.log(jj); // { p1: 1, p2: 2 } // all true console.log(jj.v === undefined); console.log(jj[v] === jj["p2"]); console.log(jj["p2"] === 2);
JavaScript, Property
- JS: Property Overview
- JS: Property Key
- JS: Property Dot Notation vs Bracket Notation
- JS: Create Property
- JS: Delete Property
- JS: Get Set Property
- JS: Check Property Existence
- JS: Access Property
- JS: List Properties
- JS: for-in Loop
- JS: Enumerable Property
- JS: Property Attributes
- JS: Property Descriptor
- JS: Getter Setter Properties