Reading Properties: Dot and Bracket Notation

Grade 8, page 3 of 13. A one-minute read.

There are two ways to read a property from an object.

Dot notation

The most common way is the dot: write the object's name, a dot, and the key.

JavaScript
const student = { name: "Omar", age: 17, favFood: "omelet" };

console.log(student.name);
console.log(student.age);
console.log(`${student.name} loves ${student.favFood}!`);

It prints

Omar
17
Omar loves omelet!

Does that dot look familiar? It should! console.log is dot notation. console is an object, and log is one of its properties. Same with Math.random, Math.PI and Number.isNaN. You've been using objects since Kindergarten without even knowing it. Sneaky, right?

Bracket notation

The other way is with square brackets and the key as a string:

JavaScript
const student = { name: "Omar", age: 17, favFood: "omelet" };

console.log(student["name"]);
console.log(student["age"]);

It prints

Omar
17

Why would you ever use the longer bracket version? Because the thing inside the brackets can be a variable (or any expression). That means you can decide which property to read while the program is running:

JavaScript
const student = { name: "Omar", age: 17, favFood: "omelet" };
const whatToShow = "favFood";

console.log(student[whatToShow]);
console.log(student.whatToShow);

It prints

omelet
undefined

student[whatToShow] looks inside the variable, finds "favFood", and reads that property. But student.whatToShow looks for a property literally named whatToShow, which doesn't exist, so it gives undefined.

TipWhich one should I use?

Use dot notation whenever you know the property name in advance (which is most of the time). Use bracket notation when the property name is stored in a variable, or when the key has spaces or other special characters.

Reading a property that doesn't exist

Just like arrays, asking for a property that isn't there gives you undefined, not an error:

JavaScript
const student = { name: "Omar" };
console.log(student.age);

It prints

undefined

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning