Create and use dynamic variable names in JavaScript

Dynamic variables are those types of variables that don’t have any specific name in the code through hard coded. A dynamic variable name is auto-generated while running the program. It is possible to create a dynamic variable in JavaScript and then using it for a specific task.

In this tutorial, I am going to show you how to create a dynamic variable and then how to use it in JavaScript. So let’s continue following this tutorial.

Here in this article, we will show you the two methods that can be followed to create dynamic variables. So let’s see…

Method 1: using eval() function

The eval() function evaluates any JavaScript code in the form of a string. For example:

eval(“myNum = 88”);

The above example will create a variable myNum and store value 88 in it.

Now below is the example of creating an adynamic variable using the eval() function:

for (var i = 0; i <= 15; i++) {
  eval("var_"+ i +" = "+i);
}

console.log(var_3);
console.log(var_9);
console.log(var_11);
console.log(var_15);

The above example will create multiple dynamic variables every time the for loop executes the code inside it.

Method 2: using the Window object

In the browser, the window object is the global object. Using it also we can create a dynamic variable which will run on our browser. Without wasting any time, let’s see below is the example of generating dynamic variables using the JavaScript window object:

for(i = 1; i < 5; i++) { 
    window['var_'+i] = + i; 
} 
  
console.log(var_1); 
console.log(var_2);
console.log(var_3);
console.log(var_4);
console.log(var_5);

Now if you run the above code, then it will be proven that our code is successfully able to generate variable names dynamically.

 

Leave a Reply