JavaScript Computed Property Name Tutorial

In this section, we will learn what the computed property is and how to use it in JavaScript.

What is JavaScript Computed Property Name?

Usually, when we want to create the properties of an object literal, we set those names explicitly.

For example:

const car = {
        model: "BMW i6",
        price: 100,
        year: 2020
      }

Here, the names for the properties of the `car` object are explicitly set.

These names are essentially static. This means at compile time, the compiler knows these names.

But there’s another way of declaring the name of properties in an object which is called computed property name. Property declaration in this way actually occurs dynamically and at runtime.

First, let’s see an example and then we will explain the details.

Example: creating computed property name in JavaScript

const prop = "model";
const car = {
  [prop]: "BMW i6",
  price: 100,
  year: 2020
}
console.log(car.model);

Output:

BMW i6

How to Create Computed Property Name in JavaScript?

In the `car` object we have one computed property which is:

[prop]: "BMW i6"

The [prop] is a runtime computed property. This means when the execution engine sees such property, it will evaluate the content in the pair of brackets `[]` and replace the result as the property name of the target object.

So here the `prop` is a constant identifier with the value `model`. So the execution engine will get the value of this identifier (model) and replace the `[prop]` with this value.

At the end, the `car` object will look like this at runtime:

const car = {
        model: "BMW i6",
        price: 100,
        year: 2020
      } 

For this reason, when in the example above, the execution engine reached to the statement:

console.log(car.model);

The engine knows that the property `model` is in this object and so it will get its value and send it to the browser’s console.

That’s how we got the message “BMW i6” on the console.

Example: computed property in JavaScript object

const prop = "rice";
const car = {
  model: "BMW i6",
  [`p${prop}`]: 100,
  year: 2020
}
console.log(car.price);

Output:

100

The computed property in this example is:

[`p${prop}`]

Here, the execution engine first resolves the `${prop}` part.

So the value of the `prop` identifier will be replaced with the `${prop}` call.

After that, the computed property becomes something like this:

["price"]

Finally, the execution engine considers the `price` as the property of the `car` object.

That’s how the `price` property was added to the `car` object.

Leave a Reply