Open In App

How to use dynamic variable names in JavaScript ?

Improve
Improve
Like Article
Like
Save
Share
Report

In programming, dynamic variable names don’t have a specific name hard-coded in the script. They are named dynamically with string values from other sources. Dynamic variables are rarely used in JavaScript. But in some cases they are useful. Unlike PHP, there is no special implementation of dynamic variable names in JavaScript. However similar results can be achieved by using some other methods.

In JavaScript, dynamic variable names can be achieved by using 2 methods/ways given below:

JavaScript eval() Method

The eval() function evaluates JavaScript code represented as a string in the parameter. A string is passed as a parameter to eval(). If the string represents an expression, eval() evaluates the expression. Inside eval(), we pass a string in which variable value i is declared and assigned a value of i for each iteration. The eval() function executes this and creates the variable with the assigned values. The code given below implements the creation of dynamic variable names using eval(). 

Example: In this example, we will see the use eval() function.

javascript




let k = 'value';
let i = 0;
for (i = 1; i < 5; i++) {
    eval('var ' + k + i + '= ' + i + ';');
}
console.log("value1=" + value1);
console.log("value2=" + value2);
console.log("value3=" + value3);
console.log("value4=" + value4);


Output

value1=1
value2=2
value3=3
value4=4

Window object

JavaScript always has a global object defined. When the program creates global variables they’re created as members of the global object. The window object is the global object in the browser. Any global variables or functions can be accessed with the window object. After defining a global variable we can access its value from the window object. The code given below implements dynamic variable names using the window object. So, the code basically creates a global variable with the dynamic name “valuei” for each iteration of i and assigns a value of i to it. Later these variables can be accessed in the script anywhere as they become global variables. 

Example: In this example, we will use the window object.

javascript




let i;
for (i = 1; i < 5; i++) {
    window['value' + i] = + i;
}
 
console.log("value1=" + value1);
console.log("value2=" + value2);
console.log("value3=" + value3);
console.log("value4=" + value4);


Output:

value1=1
value2=2
value3=3
value4=4

JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.



Last Updated : 22 Dec, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads