JS: Dot vs bracket syntax for property access

By Xah Lee. Date: . Last updated: .

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:

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

Function forms for get set property