tags:

views:

940

answers:

5

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

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

How can i declare variable varName?

+1  A: 

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

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

Does that work?

Daniel Magliola
how can i go about the problem?
Babiker
A: 

there may be a better way but eval should do it

eval('var ' + foo + bar);

SpliFF
@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
+3  A: 

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
An additional reason to not use eval is that strict mode ECMAScript 5 does not allow eval to inject new variables
olliej
+1  A: 

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.

harto
A: 

Locally:

this[foo+bar] = true;

Globally:

window[foo+bar] = true;
Karl Guertin