How to use a Variable for a Key in a JavaScript Object Literal?
Last Updated :
11 Oct, 2024
Improve
Using a variable as a key in a JavaScript object literal enables dynamic property creation, allowing us to define object properties based on variable values.
Syntax:
let key="your_choice";
let object = {};
object[key] = "your_choice";
console.log(object);
Example: This shows how to use a variable for a key.
let key = "Geeksforgeeks";
let object = {};
object[key] = "something";
console.log(object);
Output
{ Geeksforgeeks: 'something' }