How to use a variable for a key in a JavaScript object literal?

In ES5 and earlier, you could not use a variable as a property name inside an object literal. The only option you had was to create the object literal, assign the variable property name with value and pass the resulting object to the animate method. ES6 defines ‘ComputedPropertyName’ as part of the grammar for object literals, which helps use a variable for a key. Object keys can be dynamically assigned in ES6 by placing an expression in square brackets.

Syntax:

var key="your_choice";
var object = {};
object[key] = "your_choice";
console.log(object);

Example 1: This shows how to use a variable for a key.



filter_none

edit
close

play_arrow

link
brightness_4
code

<html>
  
<head>
    <title>
        How to use a variable for a
      key in a JavaScript object literal?
    </title>
</head>
  
<body style="text-align:center;">
    <h1 style="color:green;">  
GeeksForGeeks  
</h1>
    <script>
        var key = "Geeksforgeeks";
        var object = {};
        object[key] = "something";
        console.log(object);
    </script>
</body>
  
</html>

chevron_right


Output:



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.