🧮 Computed Properties
Computed properties allow you to create object properties dynamically using an expression in square brackets [].
Here’s the syntax of the computed property:
let propertyName = 'dynamicPropertyName';
const obj = {
[propertyName] : value
}In this syntax:
propertyNameis a variable that stores the property name.[propertyName]is a computed property name of the object literalobj. The property name is derived from the value of thepropertyNamevariable.valueis the value of the computed property, which can be any valid JavaScript expression.
Once you define a computed property, you can access it as follows:
obj.dynamicPropertyName1) Basic JavaScript computed property example :
let propName = 'c';
const rank = {
a: 1,
b: 2,
[propName]: 3,
};
console.log(rank.c); // 3📌 Explanation:
propName = 'c'holds the dynamic key.[propName]becomes'c'during object creation.So the object becomes:
{ a: 1, b: 2, c: 3 }.Accessing
rank.creturns3.
2) Using a computed property in a class :
const name = "fullName";
class Person {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
get [name]() { // computed getter name
return `${this.firstName} ${this.lastName}`;
}
}
let person = new Person("John", "Doe");
console.log(person.fullName); // John Doe✨Explanation:
name = 'fullName'is used as the method name.get [name]()becomesget fullName()at runtime.When
person.fullNameis accessed, it calls the computed getter and returns"John Doe".
3) Creating an object from a key/value pair :
const createObject = (key, value) => {
return {
[key]: value,
};
};
const person = createObject('name', 'John');
console.log(person); // { name: 'John' }🟢 Explanation:
[key]: valueis a computed property.key = 'name'becomes the object's key.The returned object is
{ name: 'John' }.