CodeBlanks Logo Icon CodeBlanks

Property access

Learn to access properties with . and [].

Property access

There are two ways to access an object's property: the dot and the bracket. Both give the same result, but they fit different situations.

Dot notation: user.name. When the property name is a valid identifier (letters, digits, underscore; not starting with a digit) the dot is preferred. It is shorter and clearer.

Bracket notation: user['name']. When the name contains spaces or hyphens, or is computed at runtime, brackets are required. Example: user['full name'] cannot be written with a dot.

Dot or bracket?

When choosing between dot and bracket, look at the structure of the property name. If it is a valid identifier and known up front, the dot is best. If the name comes from a variable, contains spaces, or uses special characters like hyphens, you must use brackets.

Dynamic access example: const key = 'age'; console.log(user[key]). Here key carries the name, so brackets are required; writing user.key would look for a property literally named 'key' and return undefined.

Accessing a missing property returns undefined in both notations; no error is thrown. So to check existence you can use user.name !== undefined or 'name' in user.

Practice Print a product's price

Define a product object as { name: 'Kalem', price: 25, stock: 100 }. Access the price property with brackets (product['price']) and print it with console.log.

Starter code

index.js
// Define the product object, print price using brackets

Sample solution

index.js
const product = { name: 'Kalem', price: 25, stock: 100 };
console.log(product['price']);

Expected output

25

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Access with brackets

Question
const user = { name: 'Ayşe', age: 30 };
console.log(user[____]);
Answer
const user = { name: 'Ayşe', age: 30 };
console.log(user['name']);

Explanation: user['name'] is the bracket access.

2 When are brackets required?

  • When the name is short
  • When the name has a space Correct answer
  • When the object is large
  • When the value is numeric

Explanation: names with spaces cannot use the dot.

3 Match the access forms

Term Meaning
user.name Dot access
user['name'] Bracket access
user[key] Dynamic access
undefined Result of a missing property

All lessons in Beginner