JS: Property Dot Notation vs Bracket Notation

By Xah Lee. Date: . Last updated: .

Dot Notation and Bracket Notation are two different ways to access property.

Dot notation

object.key

Dot notation. Most convenient.

const xx = { dogs: 33 };
console.assert(xx.dogs === 33);

Dot notation cannot be used when:

Dot operator associate to the left.

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

// create a empty object
const jj = {};

// a property name
const xvar = "dog";

jj[xvar] = 2;

console.assert(Object.hasOwn(jj, "xvar") === false);
console.assert(Object.hasOwn(jj, "dog"));
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 notation, but return undefined instead of error if object is undefined or null

Function forms for get set property