Skip to content

JavaScript Tutorial Objects

Computed Properties and Shorthand in JavaScript Objects

Lesson 83 of 258 2 min read By Deepak Paswan Updated Oct 4, 2026

Computed property names

Wrap an expression in square brackets to use its value as the key.

script.js
JS
const field = "email";

const user = {
  name: "Maya",
  [field]: "maya@example.com"
};

console.log(user); // → { name: Maya, email: maya@example.com }

Any expression works:

script.js
JS
const id = 7;
const lookup = { ["user_" + id]: "Maya", [`${id}-label`]: "seven" };
console.log(lookup); // → { user_7: Maya, 7-label: seven }

Why it is useful: dynamic keys

Updating a form field by its name:

script.js
JS
function setField(state, name, value) {
  return { ...state, [name]: value };
}

let form = { email: "", name: "" };
form = setField(form, "email", "maya@example.com");
console.log(form); // → { email: maya@example.com, name:  }

Counting words:

script.js
JS
const counts = {};
for (const word of ["a", "b", "a"]) {
  counts[word] = (counts[word] ?? 0) + 1;
}
console.log(counts); // → { a: 2, b: 1 }

Shorthand properties

When a variable name equals the key, write it once.

script.js
JS
const title = "Hello";
const views = 120;

const post = { title, views };
console.log(post); // → { title: Hello, views: 120 }

Shorthand methods

script.js
JS
const calculator = {
  add(a, b) { return a + b; }     // same as add: function (a, b) { ... }
};

Putting it together

script.js
JS
function createProduct(name, price) {
  return {
    name,
    price,
    describe() {
      return `${this.name}: $${this.price}`;
    }
  };
}

console.log(createProduct("Pen", 2).describe()); // → Pen: $2
info
Map for dynamic keys
If you have many dynamic keys, or keys that are not strings, a Map is often a better fit than an object.