Open In App

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

Last Updated : 17 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads