JavaScript Computed Properties

Computed properties let you use an expression or variable as a property key inside an object literal. You wrap the expression in square brackets [ ], and JavaScript evaluates it to produce the actual key name. This removes the need to define an object first and then add dynamic keys separately.

The Problem Without Computed Properties

let field = "username";
let value = "anjali_92";

// Old way — two steps:
let user = {};
user[field] = value;

console.log(user); // { username: "anjali_92" }

Computed Properties: One Step

let field = "username";
let value = "anjali_92";

// New way — inline in the object literal:
let user = {
  [field]: value
};

console.log(user); // { username: "anjali_92" }

The brackets tell JavaScript: "evaluate this expression and use its result as the key name."

Diagram: Computed Property Evaluation

let key = "color";

Object literal:
  { [key]: "red" }
        │
   JavaScript evaluates key → "color"
        │
   Result: { color: "red" }

Using Expressions as Keys

Any expression that produces a string (or a value that converts to a string) can be a computed key.

let prefix = "user";

let profile = {
  [prefix + "Name"]: "Rohan",
  [prefix + "Age"]:  28,
  [prefix + "City"]: "Mumbai"
};

console.log(profile);
// { userName: "Rohan", userAge: 28, userCity: "Mumbai" }

Diagram: Expression Building a Key

prefix = "user"

[prefix + "Name"]  → "user" + "Name" → "userName"
[prefix + "Age"]   → "user" + "Age"  → "userAge"
[prefix + "City"]  → "user" + "City" → "userCity"

Using Variables from a List

Computed properties work well when you build objects from a list of field names.

let fields = ["name", "email", "phone"];
let values = ["Meera", "meera@mail.com", "9876543210"];

let contact = {};
fields.forEach(function(field, index) {
  contact[field] = values[index];
});

console.log(contact);
// { name: "Meera", email: "meera@mail.com", phone: "9876543210" }

Dynamic Keys in Forms or Settings

A common real-world pattern: updating a specific field in a state object based on which form input changed.

function updateField(state, fieldName, newValue) {
  return {
    ...state,
    [fieldName]: newValue  // computed key from parameter
  };
}

let formState = {
  name: "Kiran",
  email: "kiran@mail.com"
};

let updated = updateField(formState, "email", "new@mail.com");
console.log(updated);
// { name: "Kiran", email: "new@mail.com" }

Diagram: Dynamic State Update

fieldName = "email"

{ ...state, [fieldName]: "new@mail.com" }
             │
     evaluates to "email"
             │
Result: { name: "Kiran", email: "new@mail.com" }

Using Symbol as a Computed Key

You can use a Symbol as a computed key to create a truly private or unique property name.

let id = Symbol("id");

let product = {
  name: "Laptop",
  price: 55000,
  [id]: "P-00123"  // Symbol key
};

console.log(product.name);  // "Laptop"
console.log(product[id]);   // "P-00123"
console.log(product["id"]); // undefined — Symbol keys are not strings

Computed Keys in Classes

Class methods can also use computed keys.

let action = "greet";

class Robot {
  [action]() {
    return "Hello from the robot!";
  }
}

let r = new Robot();
console.log(r.greet()); // "Hello from the robot!"

Combining Computed Properties with Destructuring

Computed keys also work in destructuring to extract a property whose name is stored in a variable.

let key = "score";
let data = { score: 95, name: "Tanvi" };

let { [key]: playerScore } = data;
console.log(playerScore); // 95

Diagram: Computed Destructuring

key = "score"
data = { score: 95, name: "Tanvi" }

{ [key]: playerScore } = data
          │
   evaluates key → "score"
          │
   extracts data["score"] → 95
          │
   assigns to playerScore

Building Objects from API Responses

Computed properties help reshape data returned from an API into a different structure.

let apiData = [
  { id: "A1", label: "Home" },
  { id: "B2", label: "About" },
  { id: "C3", label: "Contact" }
];

// Build an object keyed by id
let pageMap = {};
apiData.forEach(function(item) {
  pageMap[item.id] = item.label;
});

console.log(pageMap);
// { A1: "Home", B2: "About", C3: "Contact" }

console.log(pageMap["B2"]); // "About"

Summary Table

SyntaxWhat the Key Is
{ name: "Raj" }Literal string "name"
{ [key]: "Raj" }Value of the variable key
{ ["user" + "Name"]: "Raj" }Result of expression → "userName"
{ [Symbol()]: "secret" }A unique Symbol key

Summary

Computed properties let you build object keys dynamically using variables or expressions inside square brackets. They replace the two-step pattern of creating an empty object and then adding dynamic keys. Computed properties appear in object literals, destructuring, and class method definitions. They are especially useful when building objects from user input, API data, form fields, or any situation where property names are not known until runtime.

Leave a Comment

Your email address will not be published. Required fields are marked *