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.

Dot notation cannot be used when:

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

JavaScript. Access Properties