Friday, September 5, 2025
HomeLanguagesJavascriptHow to declare object with computed property name in JavaScript ?

How to declare object with computed property name in JavaScript ?

In this article, we learn how to declare an object with a computed property name. Before beginning this article, we have to know about the javascript objects.

Computed Property Names: The ES6 computed property names feature allows us to compute an expression as a property name on an object.

Javascript Object: Javascript objects contain key-value pairs in which the key represents a property from which we can get and set the value of the object. Now we will see how to declare an object with a computed property name. 

Method 1: We will use the expression within the [ ] (square bracket) to create the name of an object property. In ES6, it is possible to use an expression within brackets ‘[ ]’. Depending on the result of the expression, a property name will be assigned to an object. 

Example: This example shows the use of the above-explained approach.

JavaScript




let LAST_NAME = "lastname";
let fullname = {
    firstname: "somya",
    [LAST_NAME]: "jain"
};
console.log(
    "My fullname is: " + fullname.firstname
    + " " + fullname.lastname
);


Output:

My fullname is: somya jain

Method 2: In this method, We will create the property name of an object dynamically. As part of this method, we will dynamically create an object and add a property name and assign a value to that specific property in order to create a customized key-value pair.  

Syntax:

objectname["name of the property name"]=value

Example: This example shows the use of the above-explained approach.

Javascript




let LAST_NAME = "lastname";
let fullname = {
    firstname: "somya"
};
fullname[LAST_NAME] = "jain";
console.log(
    "My fullname is: " + fullname.firstname
    + " " + fullname.lastname
);


Output:

My fullname is: somya jain
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32264 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6634 POSTS0 COMMENTS
Nicole Veronica
11801 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11863 POSTS0 COMMENTS
Shaida Kate Naidoo
6750 POSTS0 COMMENTS
Ted Musemwa
7025 POSTS0 COMMENTS
Thapelo Manthata
6701 POSTS0 COMMENTS
Umr Jansen
6718 POSTS0 COMMENTS