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:
- Property key contains space, hypen, question mark, etc. E.g.
{"a?":7}or{"a-b":7} - Property key is a language keyword or reserved word. E.g.
obj.for. - Property key is digits. E.g.
obj.7 - Property key as value of a variable.
- Property key is Symbol type.
const xx = { "pp": 33 }; console.assert(xx.pp === 33);
dot notation associate to the left.
x.y.z
means
(x.y).z
not
x.(y.z)
Bracket Notation
object[key]
Bracket notation. Useful if key contains space or is a number or Symbol type, or is a variable.
// creating a property, with name from a value of variable // dot notation won't work // create a empty object const jj = {}; // a property name const xvar = "pp"; jj[xvar] = 2; console.assert(Object.hasOwn(jj, "xvar") === false); console.assert(Object.hasOwn(jj, "pp") === true); console.assert(jj["pp"] === 2);
const x = {}; // property name that contains space x["a b"] = 1; // a property with name that's a digit x["3"] = 1; // a property name containing hyphen x["p-a"] = 1; // property name containing question mark x["p?"] = 1; console.assert(x["a b"] === 1); console.assert(x["3"] === 1); console.assert(x["p-a"] === 1); console.assert(x["p?"] === 1);
Optional Chaining Operator
object ?. key
Same as dot notation, but return undefined instead of error out if object is undefined or null
Function form for get set property, using Reflect
JavaScript. Property
- JS: Property Overview
- JS: Order of Properties
- 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 Property