JavaScript Fundamentals / Classes

Computed Properties

🧮 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:

  • propertyName is a variable that stores the property name.

  • [propertyName] is a computed property name of the object literal obj . The property name is derived from the value of the propertyName variable.

  • value is 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.dynamicPropertyName

1) 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.c returns 3.


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]() becomes get fullName() at runtime.

  • When person.fullName is 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]: value is a computed property.

  • key = 'name' becomes the object's key.

  • The returned object is { name: 'John' }.