Property access
Learn dot and bracket notation for property access and when to use each.
Dot notation
To access a property of an object, use dot notation: write the object name, a dot, and the property name.
const user = { name: 'Alex', age: 28 };
user.name; // 'Alex'
user.age; // 28Dot notation is readable and ideal when you know the property name. The property name must be a valid identifier; it cannot contain spaces or hyphens.
Bracket notation
When the property name is stored in a variable or is not a valid identifier (has spaces or hyphens), use bracket notation.
const user = { 'full name': 'Alex Stone' };
const key = 'age';
user['full name']; // 'Alex Stone'
user[key]; // 28Inside the brackets the key is written as a string. With a variable you skip the quotes, which makes dynamic access possible.
Exercise Calculate the total price
Access the price and quantity properties of the cart object below and assign their product to a total variable. Print total with console.log.
Show example solution
const cart = { price: 25, quantity: 4 };
const total = cart.price * cart.quantity;
console.log(total);
Test yourself
-
What does user.name return?
const user = { name: 'Alex', age: 28 }; user.name;- 28
- undefined
- 'Alex'
- name
Show answer
'Alex' — Correct! user.name returns the value of the name property.
-
Access with a variable
const user = { age: 28 }; const key = 'age'; user____;Show answer
const user = { age: 28 }; const key = 'age'; user[key]; -
Match each access form
- user.name
- dot notation
- user['name']
- bracket notation
- user[key]
- dynamic access