JavaScript Computed Property Names Explained
Computed property names allow developers to dynamically generate and assign object keys at the time of object creation using JavaScript expressions. Introduced in ECMAScript 2015 (ES6), this feature replaces older multi-step assignment workarounds by enabling bracket notation directly inside object literals. This article explains how computed property names work, their underlying syntax, and practical examples for using them effectively.
The Syntax
To use a computed property name, wrap any valid JavaScript expression
in square brackets ([]) on the left side of the colon
inside an object literal:
const keyName = 'status';
const user = {
name: 'Alex',
[keyName]: 'Active'
};
console.log(user.status); // "Active"Prior to ES6, assigning a dynamic property required creating the object first and assigning the property via bracket notation on a separate line:
// Pre-ES6 Approach
var user = { name: 'Alex' };
user[keyName] = 'Active';Computed property names streamline this process by allowing the dynamic key to be declared directly within the literal definition.
How Evaluation Works
When the JavaScript engine parses an object literal, it evaluates the expression inside the brackets immediately. The evaluated result is converted to a string (or remains a Symbol) to serve as the property identifier.
You can use variables, arithmetic operations, template literals, or function calls within the brackets:
const prefix = 'data_';
let id = 42;
function getKey() {
return 'accessLevel';
}
const report = {
[prefix + id]: 'Sensor Payload',
[`user_${id}`]: 'John Doe',
[getKey()]: 'Admin',
[2 + 3]: 'Five'
};
console.log(report.data_42); // "Sensor Payload"
console.log(report.user_42); // "John Doe"
console.log(report.accessLevel); // "Admin"
console.log(report['5']); // "Five"Common Use Cases
1. Dynamic State Updates
Computed property names are widely used in modern UI frameworks (such as React) to manage dynamic input forms using a single handler function:
function updateField(state, name, value) {
return {
...state,
[name]: value
};
}
const currentState = { username: '', email: '' };
const updatedState = updateField(currentState, 'email', 'user@example.com');2. Working with Symbols
Symbols are primitive values often used to create unique, non-colliding object keys. Computed properties allow Symbols to be integrated directly inside the object definition:
const uniqueID = Symbol('id');
const device = {
[uniqueID]: 'DEV-9921',
model: 'X1'
};
console.log(device[uniqueID]); // "DEV-9921"3. Computed Method Names
Computed property syntax can also be applied to object methods and class definitions:
const action = 'execute';
const service = {
[action]() {
return 'Action executed successfully.';
}
};
console.log(service.execute()); // "Action executed successfully."