0

To assign a value to a variable is very simple just do it this way

var foo = "bar";

But to assign a name to the variable (dynamically) as you have to do?

var variableName = "newName";
var variableName = "bar";    // in this case assign new value of variableName

Do I have to do it this way?

var foo + "_" + variableName = "foo"  // foo_newName = "bar"
8
  • i don think this is possible in javascript...you are trying to create variable name dynamically ...how is that possible it not about javascript it not possible in c# also as per my knowldege Commented Jul 27, 2015 at 7:23
  • Why do you need this functionality? Commented Jul 27, 2015 at 7:24
  • 2
    You can only have dynamic properties of objects (including the global object, window, if you like), but not local variables. Commented Jul 27, 2015 at 7:24
  • variables are nothing but identifiers and they store some value, and any mathematical operation you intend are going to be performed on the values. I can't think what exactly you are trying to solve? creating dynamic variables and accessing them conditionally is native to any programming language including gw-basic : ) Commented Jul 27, 2015 at 7:24
  • it is possible only if your variables are global or under some scope. Commented Jul 27, 2015 at 7:25

3 Answers 3

10

You can make dynamic variable using this way

window['varname'] = "test";

alert(varname);

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

2 Comments

Thanks is what I was looking for
No problem, Please accept the answer if it worked to you. Happy coding.
4

You can do that by using eval(), but there are some Reservations about using that method:

eval("foo_" + i + "='bar'")

2 Comments

What reservations would those be?
Hii This function is used in different languages but Using it (specifically) with javascript on client side (browser) is not that bad. Here is a link about eval function: stackoverflow.com/questions/197769/…
2

As per my understanding, you can not create variables like this, however, you can use object and set its property.

var foo = "bar";
var variableName = "newName";

window[foo + "_" + variableName]  = "foo" ;
console.log(bar_newName);

or

var foo = "bar";
var variableName = "newName";

var obj = {};

obj[foo + "_" + variableName]  = "foo" ;
console.log(obj["bar_newName"]);

Comments

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.