A computed property in a JavaScript object is a way to dynamically define property keys using an expression inside square brackets ([]). This allows the key to be evaluated at runtime, making it possible to create properties based on variables, function calls, or other expressions. Here’s an example:
const keyName = 'dynamicKey';
const obj = {
[keyName]: 'value'
};
console.log(obj.dynamicKey); // Output: value
In this example:
- The property key dynamicKey is computed using the variable keyName.
- When obj is created, keyName is evaluated, resulting in a property dynamicKey with the value "value".
Common Use Cases
1. Creating properties based on variable values:
function createObject(propName, value) {
return {
[propName]: value
};
}
const newObj = createObject('name', 'Alice');
console.log(newObj.name); // Output: Alice
2. Using expressions for dynamic keys:
const obj = {
['prop_' + (1 + 2)]: 'Computed Property'
};
console.log(obj.prop_3); // Output: Computed Property
Summary
Computed properties provide flexibility by allowing you to define object keys based on dynamic conditions or values at runtime.
No comments:
Post a Comment