3

How can i concatenate var names to declare new vars in javascript?:

var foo = 'var';
var bar = 'Name';

How can i declare variable varName?

Daniel Magliola
  • 30,898
  • 61
  • 164
  • 243
Babiker
  • 18,300
  • 28
  • 78
  • 125
  • 3
    Just out of curiosity, why would you need to do that? Chances are, you're doing something wrong. – Sasha Chedygov May 28 '09 at 03:06
  • It make Javascript harder to read because you can't search where declare variable by using simple search like this("var [variable name]"). –  May 28 '09 at 03:35
  • 1
    I have pre-declared var names that the user might be invoke based on user text input. – Babiker May 28 '09 at 03:40

5 Answers5

12

Try something like:

window[foo + bar] = "whatever"; 
alert(varName);

do not use the eval function unless you are absolutely certain about what's going in. window[] is much safer if all you're doing is variable access

Jonathan Fingland
  • 56,385
  • 11
  • 85
  • 79
  • 1
    An additional reason to not use eval is that strict mode ECMAScript 5 does not allow eval to inject new variables – olliej May 28 '09 at 05:18
1

WARNING: VaporCode! Off the top of my head...

window[foo + bar] = "contents of variable varName";

Does that work?

Nathaniel Ford
  • 20,545
  • 20
  • 91
  • 102
Daniel Magliola
  • 30,898
  • 61
  • 164
  • 243
1

To dynamically declare a local variable (i.e. var fooName), I guess you could use eval:

eval('var ' + foo + bar);

Best to avoid eval though, if you can avoid it (see related question).

A better way is to set an object property. Defining a global variable is equivalent to setting a property on the global object window:

window[foo+bar] = 'someVal';

You can substitute window for another object if appropriate.

Community
  • 1
  • 1
harto
  • 89,823
  • 9
  • 47
  • 61
0

Locally:

this[foo+bar] = true;

Globally:

window[foo+bar] = true;
Karl Guertin
  • 4,346
  • 2
  • 22
  • 19
-3

there may be a better way but eval should do it

eval('var ' + foo + bar);
JMax
  • 26,109
  • 12
  • 69
  • 88
SpliFF
  • 38,186
  • 16
  • 91
  • 120
  • 2
    @Babiker: Eval really is a bad practice, and dangerous, especially considering your comment about using user input to define what variable you'll be using. Not that anything a user can do in JS can be dangerous if your server is secure anyway, but still... using window[foo+bar] is definitely safer. – Daniel Magliola May 28 '09 at 03:47