Computed Property Names in JavaScript

By Hemanta Sundaray on 2023-02-08

Computed property names in JavaScript are a feature that allows you to dynamically set the property name of an object. In other words, instead of hardcoding the name of a property, you can compute it at runtime based on a value.

When we say "compute at runtime", it means that the property name is determined during the execution of the program, based on the values that are available at that moment.

For instance, let's say you have an object called person and you want to add a property to it that represents their age. Normally, you would write something like this:

const person = {
  name: "John",
  age: 30,
}

Here, the age property is hardcoded. "Hardcoded" means that the value is fixed and set directly in the code, rather than being determined at runtime. But with computed property names, you can do something like this:

const key = "age"
const person = {
  name: "John",
  [key]: 30,
}

In this example, the second property (age) is a computed property name, which uses the value of the key variable within square brackets ([]) to determine the property name.

In addition to using variables, you can also use expressions or the result of function calls to compute property names. For example:

let person = {
  ["first" + "Name"]: "John",
  ["last" + "Name"]: "Doe",
}

console.log(person)
// Output: { firstName: 'John', lastName: 'Doe' }

In this example, the expressions "first" + "Name" and "last" + "Name" are used to compute the property names firstName and lastName.

Here's another example using a function call:

function getKey(key) {
  return `${key}`
}
let person = { [getKey("firstName")]: "Jane", [getKey("lastName")]: "Doe" }

console.log(person)
// Output: {firstName: 'Jane', lastName: 'Doe'}

In this example, the function getKey() is used to compute the property names firstName and lastName.

So, computed property names in JavaScript allow you to set the property name of an object dynamically, which can be useful in situations where the property names may not be known ahead of time.

Join the Newsletter