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?

3
  • 3
    Just out of curiosity, why would you need to do that? Chances are, you're doing something wrong. Commented May 28, 2009 at 3:06
  • It make Javascript harder to read because you can't search where declare variable by using simple search like this("var [variable name]"). Commented May 28, 2009 at 3:35
  • 1
    I have pre-declared var names that the user might be invoke based on user text input. Commented May 28, 2009 at 3:40

5 Answers 5

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

Sign up to request clarification or add additional context in comments.

1 Comment

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

Comments

1

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

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

Does that work?

1 Comment

how can i go about the problem?
0

Locally:

this[foo+bar] = true;

Globally:

window[foo+bar] = true;

Comments

-3

there may be a better way but eval should do it

eval('var ' + foo + bar);

1 Comment

@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.

Your Answer

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.