-1

I'm new to JavaScript and this is a basic question but I simply can't find the answer. I've created a couple variables.

var foo1 = true;
var bar = 1;

Is there any way I can re-create my boolean variable including the value of "bar"? I'm trying to create "foo1 = false;" here:

foo+bar = false; // or
foo[+bar] = false;

None of this works of course.

treemok
  • 5
  • 2
  • 10
    Variable variables is a bad idea, use arrays and objects instead. – zerkms Aug 12 '15 at 04:25
  • 2
    What are you trying to do? What actual problem are you trying to solve? Are you trying to create a variable that includes the value of some other variable in the name of the new variable? If so, please explain why you are trying to do this as variables with unknown names are pretty much never the best way to solve a problem. You can use an object with a named property on it or an array to store multiple values. – jfriend00 Aug 12 '15 at 04:27
  • 4
    It is not possible to have dynamically named local variables. It is possible to have dynamically named global variables, given that they are properties of a global object. But as @zerkms said, what you are trying to do is almost certainly a bad idea, which makes your question an [XY problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). Please describe why you want to do what you described; I am positive there is a better way to do it. – Amadan Aug 12 '15 at 04:28
  • Agree with @zerkms. However, if you need to do this and don't want to use objects, technically you could use `eval`. – Moishe Lipsker Aug 12 '15 at 04:35
  • My plan is this: when you click on a button called "btn1" is stores the "1" and needs to change the var "foo1" to false. – treemok Aug 12 '15 at 04:47

2 Answers2

0

Is this helpful to what you're asking for? I presume where you are adding the values together you may actually be wanting to compare them for equality?

//setting variables
var foo1 = true;
var bar = 1;

//foobar1 is defined as the result of comparing foo1 and bar for deep equality, as foo1 and bar aren't the same value false is returned
var foobar1 = foo1 === bar;

snippet.log(foobar1);

//foobar2 actually returns true because it converts the 1 into true
var foobar2 = foo1 == bar;

snippet.log(foobar2);
moleyo
  • 1
  • 1
0

As others have pointed out, trying to construct variable names as strings is a Very Bad Idea. Instead make an object to keep the various values:

var foo = {};

Now, instead of

foo1 = true;

you say

foo[1] = true;

To set the value for bar:

foo[bar] = false;