Last modified: Jul 21, 2026
JavaScript Dynamic Variable Names Guide
Dynamic variable names let you create variables on the fly. This means you can name a variable using a string or an expression. It is a powerful technique in JavaScript.
Many beginners ask: "Can I create a variable with a name from user input?" Yes, you can. But you must do it safely. This guide shows you how.
We will explore three main methods. We will use objects, eval(), and the window object. Each method has pros and cons. We will also cover best practices.
Why Use Dynamic Variable Names?
Sometimes you need a variable name that changes. For example, you might have data from an API. The keys of the data could be variable names. Or you might want to create many variables in a loop.
Dynamic names help you write flexible code. They reduce repetition. But they can also make code harder to read. Use them wisely.
Let's look at a simple example. Imagine you have a list of product names. You want to store their prices in separate variables.
// Example: You want variables like priceApple, priceBanana, priceOrange
// Without dynamic names, you would write:
let priceApple = 1.5;
let priceBanana = 0.8;
let priceOrange = 1.2;
// This works but is repetitive.
With dynamic names, you can create these from an array. This is much cleaner.
Method 1: Using Objects (Recommended)
The safest and most common way is to use an object. In JavaScript, an object's properties can be accessed with bracket notation. This allows dynamic keys.
Think of the object as a container. The property names are your "dynamic variable names". This avoids global scope pollution.
// Create an empty object
let prices = {};
// Array of product names
let products = ['Apple', 'Banana', 'Orange'];
// Loop and create dynamic properties
for (let i = 0; i < products.length; i++) {
let productName = products[i];
// Use bracket notation to create a dynamic key
prices[productName] = 1.0 + i * 0.5; // Some price logic
}
// Access them
console.log(prices.Apple); // 1
console.log(prices.Banana); // 1.5
console.log(prices.Orange); // 2
1
1.5
2
This method is clean. It keeps all related variables inside one object. It is easy to read and debug.
You can also use a variable as the key. This is very flexible.
let keyName = 'userAge';
let userData = {};
userData[keyName] = 25;
console.log(userData.userAge); // 25
This is the recommended approach. It is safe and follows JavaScript best practices. For more on how variables work in different contexts, check out our JavaScript Variable Scope Explained guide.
Method 2: Using the Window Object (Global Scope)
In a browser, the global object is window. You can add properties to it. This creates global variables dynamically.
This method is simple but dangerous. It pollutes the global namespace. It can overwrite existing global variables. Use it only if you know what you are doing.
// Create a dynamic global variable
let varName = 'dynamicVar';
window[varName] = 'Hello from dynamic variable!';
// Now you can access it directly
console.log(dynamicVar); // Hello from dynamic variable!
Hello from dynamic variable!
This works because window is an object. Bracket notation adds a property. The property becomes a global variable.
But be careful. If you use a name like name or status, you might break other code. Never use this in large applications.
If you are working with global variables, you should understand JavaScript Variable Shadowing to avoid conflicts.
Method 3: Using eval() (Not Recommended)
The eval() function executes a string as JavaScript code. You can use it to create variables. But it is very dangerous.
eval() runs any code you give it. If the string comes from user input, an attacker can run malicious code. This is a major security risk.
It is also slow. The JavaScript engine cannot optimize code inside eval(). Avoid it whenever possible.
// Dangerous example using eval
let varName = 'myVar';
let varValue = 42;
// This creates a variable named myVar
eval('var ' + varName + ' = ' + varValue + ';');
console.log(myVar); // 42
42
This works, but it is bad practice. There is almost always a better way. Use objects instead.
If you must use dynamic names, never use eval() with user input. The risks are too high.
Best Practices for Dynamic Variable Names
Here are some tips to keep your code safe and clean.
Use objects. They are the safest and most readable choice. Group related variables together.
Avoid global scope. Do not pollute the window object unless absolutely necessary. It can cause hard-to-find bugs.
Never trust user input. If you use dynamic names from user data, validate it first. Use a whitelist of allowed names.
Consider Maps. For more complex cases, use a Map object. It allows any type of key, not just strings.
// Using Map for dynamic keys
let myMap = new Map();
let key1 = 'color';
myMap.set(key1, 'blue');
console.log(myMap.get('color')); // blue
Keep it simple. If you need many dynamic variables, rethink your data structure. An array or object is often better.
For a deeper understanding of how to handle variable names, see our JavaScript Variable Naming Rules article.
Common Use Cases
Dynamic variable names appear in many real-world scenarios.
Form data. When you submit a form, you get key-value pairs. You can store them in an object dynamically.
API responses. JSON data often has dynamic keys. You can access them with bracket notation.
Configuration objects. You might have settings that change. Dynamic keys let you update them easily.
// Example: Dynamic keys from API data
let apiData = {
"user_123": { name: "Alice", age: 30 },
"user_456": { name: "Bob", age: 25 }
};
// Access a dynamic user ID
let userId = "user_123";
console.log(apiData[userId].name); // Alice
Alice
This pattern is very common. It makes your code adaptable.
Conclusion
Dynamic variable names are a useful tool in JavaScript. The best way to create them is by using objects and bracket notation. This method is safe, readable, and efficient.
Avoid eval() and be careful with the window object. Always think about security and code clarity.
Now you know how to create variables with names that change at runtime. Use this knowledge to write more flexible JavaScript code. Practice with the examples above to get comfortable.