How do I Create Dynamic Variable Names Inside a JavaScript Loop?

Creating dynamic variable names inside a JavaScript loop means generating variable names programmatically during runtime rather than hardcoding them. This technique is useful when you need to create multiple variables based on user input, API responses, or iterative patterns.

In this article, we'll explore four different approaches to create dynamic variable names inside a JavaScript loop, with practical examples and best practices.

Approaches to Create Dynamic Variable Names

Here are the four main approaches we'll cover, each with different use cases and considerations:

Using Array (Recommended)

Arrays provide the simplest and most efficient way to store dynamically created values. Instead of creating separate variables, we use array indices to simulate dynamic variable names.

Example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dynamic Variables with Array</title>
</head>
<body>
    <h2>Creating Dynamic Variable Names using Array</h2>
    <p>Click the button to create dynamic variables using an array.</p>
    <button onclick="createVariable()">Create Variables</button>
    <div id="output"></div>

    <script>
        let dynamicVars = [];
        
        function createVariable() {
            // Create 5 dynamic variables
            for (let i = 0; i < 5; i++) {
                dynamicVars[i] = 'Variable ' + i + ' value';
            }
            
            // Display the results
            let output = '';
            for (let i = 0; i < dynamicVars.length; i++) {
                output += 'dynamicVars[' + i + '] = ' + dynamicVars[i] + '<br>';
            }
            
            document.getElementById("output").innerHTML = output;
            console.log(dynamicVars);
        }
    </script>
</body>
</html>

Using eval() Function (Not Recommended)

The eval() function executes JavaScript code represented as a string. While it can create dynamic variables, it's generally discouraged due to security and performance concerns.

Example

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Dynamic Variables with eval()</title>
</head>
<body>
    <h2>Creating Dynamic Variable Names using eval()</h2>
    <p>This approach uses eval() function (not recommended for production).</p>
    <button onclick="createVar()">Create Variables</button>
    <div id="output"></div>

    <script>
        function createVar() {
            // Create 4 dynamic variables using eval()
            for (let i = 0; i < 4; i++) {
                eval("var item" + i + " = 'Item " + i + "';");
            }
            
            // Display the created variables
            document.getElementById("output").innerHTML =
                item0 + "<br>" + item1 + "<br>" + item2 + "<br>" + item3;
        }
    </script>
</body>
</html>

Using Map Object (Recommended for Complex Cases)

The Map object provides a clean way to create key-value pairs dynamically. It offers better performance than objects for frequent additions and deletions.

Example

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Dynamic Variables with Map</title>
</head>
<body>
    <h2>Creating Dynamic Variable Names using Map</h2>
    <p>Map objects provide a clean way to store dynamic key-value pairs.</p>
    <button onclick="createVar()">Create Variables</button>
    <div id="output"></div>

    <script>
        function createVar() {
            let dynamicVars = new Map();
            
            // Create 5 dynamic variables using Map
            for (let i = 0; i < 5; i++) {
                dynamicVars.set("item" + i, "Item " + i + " value");
            }
            
            // Display the results
            let output = '';
            for (let [key, value] of dynamicVars) {
                output += key + ' = ' + value + '<br>';
            }
            
            document.getElementById("output").innerHTML = output;
            console.log(dynamicVars);
        }
    </script>
</body>
</html>

Using window Object (Not Recommended)

The window object represents the browser's global scope. While you can create global variables this way, it can lead to naming conflicts and memory leaks.

Example

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Dynamic Variables with window Object</title>
</head>
<body>
    <h2>Creating Dynamic Variable Names using window Object</h2>
    <p>This approach creates global variables (use with caution).</p>
    <button onclick="createVar()">Create Variables</button>
    <div id="output"></div>

    <script>
        function createVar() {
            // Create 4 dynamic global variables
            for (let i = 0; i < 4; i++) {
                window["item" + i] = "Item " + i + " value";
            }
            
            // Display the created variables
            document.getElementById("output").innerHTML =
                item0 + "<br>" + item1 + "<br>" + item2 + "<br>" + item3;
        }
    </script>
</body>
</html>

Comparison of Approaches

Method Security Performance Recommended Use Case
Array Safe Excellent Yes Simple indexed storage
Map Object Safe Excellent Yes Complex key-value pairs
eval() Risky Poor No Avoid in production
window Object Risky Poor No Legacy code only

Best Practices

  • Use Arrays for simple indexed storage of dynamic values
  • Use Map objects when you need named keys and complex data structures
  • Avoid eval() due to security vulnerabilities and performance issues
  • Avoid window object to prevent global namespace pollution
  • Consider using regular objects {} as an alternative to Maps for simple cases

Conclusion

For creating dynamic variable names in JavaScript loops, Arrays and Map objects are the recommended approaches. Arrays work best for simple indexed storage, while Maps excel with complex key-value relationships. Avoid eval() and window object methods in production code due to security and maintainability concerns.

Updated on: 2026-03-15T21:31:40+05:30

17K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements