by Sai gowtham

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

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
26,545 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
221,520 students enrolled
44 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
114,575 students enrolled
21 hours of video content
View Course