JS: Dot vs bracket syntax for property access
Dot Syntax and Bracket Syntax are two different ways to access property.
Dot syntax
object.key
Dot syntax. Most convenient.
const xx = { dogs: 33 }; console.assert(xx.dogs === 33);
Dot syntax 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 is Symbol type.
- You want a variable's value as property key.
Dot syntax associate to the left
dot syntax associate to the left.
x.y.z
means
(x.y).z
not
x.(y.z)
Bracket syntax
object[key]
Bracket syntax. 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 // create a empty object const jj = {}; // a property name const xvar = "dog"; jj[xvar] = 2; console.assert(jj["dog"] === 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 syntax, but return undefined instead of error if object is undefined or null