0

This is more of a syntax question, but I couldn't quite google it properly.

Say I have 2 variables:

classHours = 127;
currentNumber = 3;

How would I NAME a variable based off these numbers?

So let's say I wanted a variable named

classHours + "pop_up" + currentNumber 

How would I go about that?

Felix Kling
820k181 gold badges1.1k silver badges1.2k bronze badges
asked Oct 20, 2014 at 15:08
4
  • 4
    There are ways to do that, but they are not common accepted practice in JavaScript. What problem are you trying to solve by doing this? There are other more idiomatic ways of creating and accessing lists and maps of values. Commented Oct 20, 2014 at 15:10
  • 3
    Typically whenever you think you need to do something like this, you'd use arrays or objects instead. Commented Oct 20, 2014 at 15:12
  • yes, @Pointy and Juhana are right. Try to searhc on dynamic variable name, or variable variable name in javascript. stackoverflow.com/questions/5117127/… Commented Oct 20, 2014 at 15:13
  • May that help you : stackoverflow.com/a/26020014/2324107 Commented Oct 20, 2014 at 15:13

2 Answers 2

2

First, your variable can't start with a numerical digit, only letters and certain special characters. I believe what you want to do is set a global variable and you can do that by using the window object. What i would recommend is creating your own object variable and using that instead. This is how you would do that:

var infoObject = {
 classHours: 127,
 currentNumber: 3
}
infoObject['pop_up'+infoObject.classHours+'_'+infoObject.currentNumber] = 'variable contents here';

However, there should normally be no reason to have to create variables in this way. What exactly are you trying to accomplish?

Felix Kling
820k181 gold badges1.1k silver badges1.2k bronze badges
answered Oct 20, 2014 at 15:22
Sign up to request clarification or add additional context in comments.

Comments

0

You could use an array with your dynamic variables, like this:

var dynamicVariables = [];
classHours = 127;
currentNumber = 3;
dynamicVariables[classHours + "pop_up" + currentNumber] = "Hey!";
alert(dynamicVariables["127pop_up3"]); // => Hey!
answered Oct 20, 2014 at 15:32

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.