Accessing Object Properties

Overview

Once a Javascript object has been created, you will often need to access the data encapsulated within the object. There are multiple ways to access an object property. Bracket Notation
The bracket notation provides a robust way to retrieve the value of a property on an object. It is not as short as the dot notation (see below), however, it can accomodate property names that have spaces or other punctuation like characters in it, and pretty much always works as a way to access an object property.

let obj = { size:20 }; let size = obj['size'];

Dot Notation

The dot notation provides an alternate way of accessing the property of an object.

let obj = { size:20 }; let size = obj.size;


There are limitations to the use of dot notation. When the property name contains certain characters (such as a space, a period, a hypen etc...) the dot notation is not allowed.

Compound Objects

Properties of an object can themselves be objects. In that case, there is a simple way to access properties down the chain.

let obj = { child:{ size:20 } }; let size = obj.child.size; let size2 = obj['child']['size']; let size3 = obj['child'].size;

Optional Chaining

When you try to access a property on a compound object that does not exist (is undefined), you will get an error. For example, in the example below, trying to access obj.child2.size in the code below would cause an error, because obj.child2 does not exist.

However, with optional chaining syntax (using ?. to access a property) the result will not throw an error, but will return undefined.

let obj = { child:{ size:20 } }; let size = obj?.child?.size; //size is 20 let size2 = obj?.child2?.size; //size2 is undefined //note obj.child2.size would throw an error.