I’m trying to create a function that can access variables dynamically by building their names using a combination of text and numbers. Right now I have this code:
function DisplayContent() {
var message_1 = "Greetings Everyone";
var counter = 1;
var variableName = 'message_' + counter;
document.getElementById("output").innerHTML = variableName;
}
The problem is that instead of getting the actual value stored in message_1, I just get the string “message_1” displayed on my page. I need to somehow convert this string into an actual variable reference so I can retrieve the content. Any help would be great!
You could use eval() but don’t - it’s a security nightmare. A better option is the window object since global variables become window properties:
function DisplayContent() {
var message_1 = "Greetings Everyone";
var counter = 1;
var variableName = 'message_' + counter;
document.getElementById("output").innerHTML = window[variableName];
}
The catch is this only works for global variables. Your variables are stuck in function scope, so you’d need to make them global first. Honestly, just use objects like the other answer suggested - way more reliable for dynamic variable access.
You could also use a Map for more flexibility. Just do let msgs = new Map(); msgs.set('message_1', 'Greetings Everyone'); then grab values with msgs.get(variableName). Perfect when you don’t know all your keys ahead of time or need to loop through them.
You’re working with the variable name as a string instead of the actual variable. Use an object to store your messages - it’s way cleaner than separate variables:
function DisplayContent() {
var messages = {
message_1: "Greetings Everyone",
message_2: "Another message"
};
var counter = 1;
var variableName = 'message_' + counter;
document.getElementById("output").innerHTML = messages[variableName];
}
Now you can grab any message dynamically with bracket notation. This beats using eval() or window properties every time - keeps everything organized and maintainable. I use this pattern all the time when I need dynamic content based on user input or counters.