How to Declare an Object with Computed Property Name in JavaScript?


In this article, we are going to explore about the concept of computed properties in an object. We will learn how to declare an object with computed property name. Let’s know about JavaScript objects before actually moving on to computed properties.

JavaScript Object − A JavaScript Object contains key-value pairs in which the key represents a property from which we can get and set the value of an object.

Method I

We will use the square bracket expression i.e. [] to create the computed name property in the object. In ES6 it is possible to use an expression within the [] brackets.

Example 1

In the below example, we are declaring an object with the computed property name.

# index.html

<html>
<head>
   <title>Computed Property</title>
</head>
<body>
   <h1 style="color: green;">
      Welcome To Tutorials Point
   </h1>
   <script>
      let LAST_NAME = "lastname";
      let fullname = {
         firstname: "Steve",
         // Defining computer property
         [LAST_NAME]: "Jobs"
      };
      console.log(
         "Full Name: " + fullname.firstname + " " + fullname.lastname
      );
   </script>
</body>
</html>

Output

On successful execution of the above program, the browser will display the following result −

Welcome To Tutorials Point

And in the console, you will find all the results, see the screenshot below −

Method II

In this method, we will be creating the property name dynamically. We will create an Object and then add a property name to it. After adding the property name, we will assign a value to that specific property in order to create the customized key-value pair.

Example 2

In the below example, we create the property name dynamically

# index.html

<html>
<head>
   <title>Computed Property</title>
</head>
<body>
   <h1 style="color: green;">
      Welcome To Tutorials Point
   </h1>
   <script>
      let LAST_NAME = "lastname";
      let fullname = {
         firstname: "Steve"
      };
      fullname[LAST_NAME] = "Jobs";
      console.log("FirstName: " + fullname.firstname + " -- LastName: " + fullname.lastname);
      console.log(
         "FullName: " + fullname.firstname + " " + fullname.lastname
      );
   </script>
</body>
</html>

Output

On successful execution of the above program, the browser will display the following result −

Welcome To Tutorials Point

And in the console, you will find all the results, see the screenshot below −

Updated on: 26-Apr-2022

343 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements