Skip to content
Related Articles

Related Articles

How to use dynamic variable names in JavaScript ?
  • Difficulty Level : Medium
  • Last Updated : 18 Nov, 2019

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. But 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.

  • eval(): 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 valuei 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 is given below implements the creation of dynamic variable names using eval().

    Example:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <script>
        var k = 'value';
        var 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);
    </script>

    chevron_right

    
    

    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 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:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <script>
        var 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);
    </script>

    chevron_right

    
    

    Output:

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

    full-stack-img




    My Personal Notes arrow_drop_up
Recommended Articles
Page :