Course contentsShow
← JavaScript
Lesson 602 of 2,72315. ObjectsFree lesson

Dynamic Property Access with Variables

Use bracket notation to access properties whose names are stored in variables.

Dynamic Property Access with Variables

You'll learn: How to use bracket notation to access object properties when the property name is stored in a variable.

The Core Idea

Sometimes you don't know which property you need to access until your program runs. Maybe a user selected a field, or you're looping through property names. When the property name lives in a variable, you must use bracket notation — dot notation won't work.

let user = {
  name: "Alice",
  age: 25,
  city: "Portland"
};

let propertyName = "name";
console.log(user[propertyName]); // "Alice"

Here, propertyName holds the string "name", and user[propertyName] accesses user.name.

Why This Matters

Dot notation is literal — user.propertyName looks for a property literally called "propertyName", not the value stored in the variable.

let field = "age";

console.log(user.field);  // undefined (no property called "field")
console.log(user[field]); // 25 (reads "age" from the variable)

Common Use Cases

Looping through property names:

let keys = ["name", "city"];

for (let i = 0; i < keys.length; i++) {
  console.log(user[keys[i]]);
}
// Logs: "Alice", "Portland"

User input:

let userChoice = "city"; // imagine this came from a form
console.log(user[userChoice]); // "Portland"

Key Takeaway: Use bracket notation object[variable] when the property name is stored in a variable — dot notation only works with literal property names you type directly.