Thursday, October 16, 2025
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

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11953 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS