Sunday, November 23, 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
32407 POSTS0 COMMENTS
Milvus
97 POSTS0 COMMENTS
Nango Kala
6785 POSTS0 COMMENTS
Nicole Veronica
11932 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12000 POSTS0 COMMENTS
Shaida Kate Naidoo
6907 POSTS0 COMMENTS
Ted Musemwa
7168 POSTS0 COMMENTS
Thapelo Manthata
6864 POSTS0 COMMENTS
Umr Jansen
6852 POSTS0 COMMENTS