Accessing Properties with Bracket Notation
You'll learn how to use square brackets to access object properties when you need flexibility or have unusual property names.
The Problem Dot Notation Can't Solve
In the previous lesson, you learned dot notation (object.property). But what if your property name is stored in a variable? Or what if the property name has spaces or special characters? Dot notation can't handle these situations — that's where bracket notation comes in.
How Bracket Notation Works
Bracket notation uses square brackets with a string (or variable containing a string) to access properties:
const person = {
name: "Alice",
age: 30
};
// Using bracket notation with a string
console.log(person["name"]); // "Alice"
console.log(person["age"]); // 30
Notice the property name is in quotes — it's a string.
Dynamic Property Access
The real power emerges when you use variables:
const person = {
name: "Alice",
age: 30
};
const propertyName = "age";
console.log(person[propertyName]); // 30 — the variable evaluates to "age"
The variable propertyName holds the string "age", so JavaScript looks up that property.
Non-Standard Property Names
Bracket notation lets you access properties that aren't valid identifiers:
const data = {
"first name": "Bob",
"favorite-color": "blue"
};
console.log(data["first name"]); // "Bob"
console.log(data["favorite-color"]); // "blue"
These wouldn't work with dot notation because spaces and hyphens aren't allowed in identifiers.
Key Takeaway: Use bracket notation when property names are dynamic (stored in variables) or when they contain characters that aren't valid identifiers — it's more flexible than dot notation but requires the property name as a string.