Skip to content
Related Articles

Related Articles

How to create dynamic values and objects in JavaScript ?
  • Last Updated : 23 Feb, 2021
GeeksforGeeks - Summer Carnival Banner

In JavaScript, you can choose dynamic values or variable names and object names and choose to edit the variable name in the future without accessing the array.

To do, so you can create a variable and assign it a particular value. Then while in the array, when you are declaring the variable use square brackets with the variable name in it, and with this when in the future you decide to change the variable name you need not access the whole array, instead you can just update the value of the variable and the variable in the array automatically changes.

Syntax:

const var_name = 'Name';
const = { [var_name] = 'GeeksForGeeks'};

Example 1:

Javascript




<script>
  const dynamic1 = "Age";
  const dynamic2 = "Marks";
  const user = {
                  Name : "GeeksForGeeks",
                  [dynamic1] : "57",
                  [dynamic2] : "42"
                };
  
  console.log(user);
</script>

Output: In this output dynamic1 is assigned the value ‘Age’, hence in the output it is shown by the name of ‘Age’, on the other hand, dynamic2 is assigned with ‘Marks’ and it is shown by the name of ‘Marks’ in the output also.



{
  Age: "57",
  Marks: "42",
  Name: "GeeksForGeeks"
}

Example 2: Let us look at what if we change the two assigned values of dynamic1 and dynamic2 respectively.

Javascript




<script>
  const dynamic1 = "Marks";
  const dynamic2 = "Age";
  const user = {
                  Name : "GeeksForGeeks",
                  [dynamic1] : "57",
                  [dynamic2] : "42"
                };
  
  console.log(user);
</script>

Output: Hence from the above code, it is clear that changing the names of the variables above the change is visible in the array attributes as well. Hence using this method we can make sure that we need not go through the array every time we wish to update any variable name or its value.

{
  Age: "42",
  Marks: "57",
  Name: "GeeksForGeeks"
}

full-stack-img

My Personal Notes arrow_drop_up
Recommended Articles
Page :