When to Use Computed vs Dot/Bracket Access
You'll learn when to compute property keys during object creation versus accessing them dynamically later.
The Core Decision
You've now seen both computed property names (using [] inside object literals) and bracket notation for property access. Both use brackets, but they solve different problems at different times:
- Computed keys at creation: Use when you know the dynamic key name while building the object
- Bracket access later: Use when you need to read/write properties after the object exists
Think of it like labeling boxes: computed keys let you print custom labels while packing the boxes (object creation), while bracket notation lets you read those labels and access contents later (object usage).
When to Compute During Creation
Use computed keys when assembling objects:
const prefix = 'user';
const id = 42;
const record = {
[prefix + 'Id']: id, // Computed at creation
[prefix + 'Name']: 'Alice'
};
// Result: { userId: 42, userName: 'Alice' }
This is cleaner than creating an empty object and adding properties afterward.
When to Access Later
Use bracket notation when working with existing objects:
const user = { userId: 42, userName: 'Alice' };
const field = 'userName';
console.log(user[field]); // 'Alice' - dynamic access
You're not creating the object here—you're retrieving values based on runtime conditions.
The Practical Rule
Creation time = computed keys. Access time = bracket notation. Sometimes you'll use both in the same workflow: compute keys when building, then access them dynamically when using the object.
Key Takeaway: Use computed property names to dynamically define keys during object creation; use bracket notation to dynamically access properties on existing objects.