Dot Notation vs Bracket Notation
What you'll learn: When to use dot notation versus bracket notation to access object properties, and why JavaScript offers both.
Two Ways to Access the Same Property
You've already seen both dot notation (object.property) and bracket notation (object["property"]). While they often accomplish the same thing, each has situations where it's required or preferred.
When Dot Notation Works
Dot notation is the cleaner, more readable option when your property name is:
- A valid JavaScript identifier (starts with a letter, contains no spaces or special characters)
- Known at the time you write the code
const user = {
name: "Alice",
age: 30
};
console.log(user.name); // "Alice" — clean and readable
When You Must Use Bracket Notation
Bracket notation is required when:
-
The property name has spaces or special characters:
const config = { "background-color": "blue" }; console.log(config["background-color"]); // must use brackets -
The property name is stored in a variable:
const key = "age"; console.log(user[key]); // 30 — dot notation can't do this -
The property name is computed or built dynamically:
const prop = "na" + "me"; console.log(user[prop]); // "Alice"
Think of It Like This
Dot notation is like using a labeled drawer — you know exactly which one to open. Bracket notation is like using a key stored in your pocket — it can open whichever drawer the key matches.
Key Takeaway: Use dot notation for clean, static property access. Use bracket notation when property names contain special characters, come from variables, or are computed at runtime.