Computed Property Names with []
You'll learn how to create object properties whose keys are determined at runtime, not hardcoded.
The Core Idea
Normally, when you write an object literal, you type the property names directly:
const user = {
name: "Alice",
age: 30
};
But sometimes you don't know the property name ahead of time—maybe it comes from a variable, a function return value, or user input. Computed property names let you wrap an expression in square brackets [] inside the object literal, and JavaScript will evaluate that expression to determine the property key.
How It Works
Instead of hardcoding the key, you compute it:
const propertyName = "favoriteColor";
const user = {
name: "Alice",
[propertyName]: "blue" // Key is computed from the variable
};
console.log(user.favoriteColor); // "blue"
The brackets tell JavaScript: "evaluate this expression first, then use the result as the property name."
You can use any expression inside the brackets:
const prefix = "user";
const id = 42;
const record = {
[prefix + "_" + id]: "Alice"
};
console.log(record.user_42); // "Alice"
Why It Matters
Before computed property names, you had to create the object first, then add the dynamic property:
const obj = {};
obj[dynamicKey] = value; // Two steps
Now you can do it in one clean declaration, making your code more readable and expressive.
Key Takeaway: Use [expression] syntax in object literals to compute property names dynamically at the moment the object is created.