Open In App

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

Last Updated : 31 Oct, 2019
Improve
Improve
Like Article
Like
Save
Share
Report

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.




<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>


Output:


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads