Computed Properties in JavaScript

🔍 What Are Computed Properties?

Computed properties in JavaScript allow you to use expressions as property names when defining objects. Instead of hardcoding a property name, you wrap an expression in square brackets [] and JavaScript evaluates it as the key. This is useful for creating dynamic object properties.

Note

💡 Introduced in ES6, computed properties let you define object keys using variables or expressions.

🧪 Basic Syntax

Using a Variable as a Key

const key = "name";

const user = {
  [key]: "Alice",
};

console.log(user.name); // "Alice"

🛠️ Use Case: Dynamic Keys

Computed properties are especially useful when you want to create keys based on function arguments or user input.

Computed Property with Function Input

function createObject(key, value) {
  return {
    [key]: value,
  };
}

const obj = createObject("age", 25);
console.log(obj); // { age: 25 }

🔁 Using Expressions as Keys

You’re not limited to just variables—you can use any expression inside [].

Expression in Computed Property

const suffix = "Id";
const user = {
  ["user" + suffix]: 101,
};

console.log(user.userId); // 101

🎯 When to Use Computed Properties

  • Creating object keys dynamically at runtime.
  • When mapping over arrays or inputs to create object structures.
  • When key names depend on logic or conditions.

⚡ Practical Example

Computed Properties in Loop

const fields = ["email", "password"];
const user = {};

fields.forEach((field, index) => {
  user[`${field}_${index}`] = true;
});

console.log(user);
// { email_0: true, password_1: true }

Note

🧠 This technique is commonly used in form generation, configuration objects, and dynamic mappings.

📚 Learn More

>>"With computed properties, your objects can adapt and grow based on logic, not hardcoded keys." 🔐