In JavaScript, Computed Properties allow you to use a dynamic expression (such as a variable or the result of a function) as an object’s property name. Instead of hardcoding a string, you wrap the expression in square brackets [] within the object literal.
This feature, introduced in ES6, eliminated the need for a multi-step process where an object had to be created first and then updated using bracket notation.
1. Basic Syntax
The value inside the square brackets is evaluated at runtime and converted into a string to serve as the key.
const keyName = "status";
const user = {
id: 1,
[keyName]: "active" // The property name becomes "status"
};
console.log(user.status); // "active"
2. Dynamic Expression Evaluation
You aren’t limited to simple variables; any valid JavaScript expression can be placed inside the brackets, including template literals and function calls.
let i = 0;
const prefix = "item_";
const collection = {
[prefix + ++i]: "First",
[prefix + ++i]: "Second",
[`${prefix}${10 * 2}`]: "Twentieth"
};
console.log(collection.item_1); // "First"
console.log(collection.item_20); // "Twentieth"
3. Practical Use Case: Form Handling
One of the most powerful applications of computed properties is handling dynamic inputs in frameworks like React or Vue. Instead of writing a separate function for every input field, you can use a single change handler.
function updateField(fieldName, value) {
const state = {
[fieldName]: value
};
// Logic to save state...
return state;
}
console.log(updateField("email", "test@example.com")); // { email: "test@example.com" }
console.log(updateField("username", "dev_user")); // { username: "dev_user" }
4. Computed Properties in Classes
Computed property names also work for methods within classes and for Getters and Setters. This is particularly useful when implementing standardized interfaces or internal symbols.
const methodName = "sayHello";
class Robot {
constructor(name) {
this.name = name;
}
[methodName]() {
return `Beep boop, I am ${this.name}`;
}
}
const bot = new Robot("R2D2");
console.log(bot.sayHello()); // "Beep boop, I am R2D2"
5. Using Symbols as Keys
Computed properties are the standard way to assign Symbols to objects. Symbols are unique identifiers that prevent property name collisions, often used for “private-ish” properties or internal hooks.
const INTERNAL_ID = Symbol('id');
const service = {
[INTERNAL_ID]: 99821,
publicName: "AuthService"
};
console.log(service[INTERNAL_ID]); // 99821
console.log(Object.keys(service)); // ["publicName"] (The symbol is hidden)
