How to use variable as an Object key in JavaScript

How to use variable as an Object key in JavaScript

In this tutorial, we are going to learn about using the variable as a key in a JavaScript object literal with the help of examples.

First way

const username = "name";

const obj = {
  [username]:"king123"}

console.log(obj.name); //output-> king123

In the above example, we first declared a variable called username then added it as an object property using square brackets syntax.

Second way

We can also use this below syntax to use the variable as an object key.

const username = "name";

const obj = {};
obj[username] = "king123";
console.log(obj.name); //output-> king123
console.log(obj[username]) // output -> king123