Saturday, November 23, 2024
Google search engine
HomeLanguagesJavascriptHow to use a variable for a key in a JavaScript object...

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.




<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 = "Geeksforneveropen";
        var object = {};
        object[key] = "something";
        console.log(object);
    </script>
</body>
  
</html>


Output:

RELATED ARTICLES

Most Popular

Recent Comments