Computed Property Names in JavaScript: A Comprehensive Guide


JavaScript objects are a powerful data structure that allows developers to store and manipulate data in a flexible and organized manner. One of the most powerful features of JavaScript objects is the ability to create properties with computed property names.

Computed property names allow developers to define the name of an object property at runtime, rather than at the time of object creation. This means that the property name can be determined based on the value of a variable or the result of an expression.

For example, consider the following code:

const key1="name";
const key2="age";
const value1="Joes";
const value2=35;
const user={
    [key1]:value1,
    [key2]:value2,
}
console.log(user);

In this example, we are using computed property names to create two properties in the user object. The property names, "name" and "age", are determined by the values of the variables key1 and key2, respectively. The values of these properties, "Joes" and 35, are determined by the values of the variables value1 and value2, respectively.

When we run the code and log the user object to the console, we get the following output:

{name: "Joes", age: 35}

As we can see, the properties of the user object have been created with the computed property names, "name" and "age", and the values, "Joes" and 35, respectively.

Computed property names can also be used in conjunction with destructuring assignment to extract values from an object. For example, the following code uses computed property names to extract the value of the "name" property from the user object:

const { [key1]: name } = user;
console.log(name); // "Joes"

Computed property names are a powerful feature of JavaScript objects that allow for more dynamic and flexible code. They can be used to create properties with dynamic names, extract values from objects, and improve code readability.

In conclusion, computed property names in JavaScript is a powerful feature that allows developers to create properties with dynamic names and extract values from objects. It makes the code more flexible and readable.

List of Programs


JS Practical Questions & Answers


JS Practical Project