Thursday, October 23, 2025
HomeLanguagesJavascriptHow to create a variable using a user-defined name in JavaScript ?

How to create a variable using a user-defined name in JavaScript ?

In this article, we will learn to create a variable using the user-defined name in JavaScript. 

Variables in JavaScript: Basically, it is a container that holds reusable data in JavaScript. The variable’s value can be changed during program execution and should be declared before using it. Before ES6 declares a variable, we just use the var keyword to create a variable, but ES6 and later, two more keywords were added to create a variable namely let and const. 

Approach:

In JavaScript, it is possible to create a variable using a user-defined name. First, we will create a variable using an object then, we will create a variable using this keyword. 

Example 1:  Create a variable using a user-defined name in JavaScript with the help of an object.

Javascript




// A user-defined variable created
let my_var = "userVariable";
let my_value = "userValue";
  
let x = {
  // Assign value of a user-defined variable
  [my_var]: my_value,
};
console.log(x);
console.log(x[my_var]);


Output:

Example 2:  Create a variable using a user-defined name in JavaScript with the help of this keyword. 

Javascript




let var_name = "newVariable";
let var_value = "newValue";
  
this[var_name] = var_value;
console.log(var_name);
console.log(this[var_name]);


Output:

newVariable
newValue

Conclusion: In this article, we learned to create a variable using the user-defined name in JavaScript with the help of two suitable approaches.

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
RELATED ARTICLES

Most Popular

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