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"
Dimitri Dewaele
  • 10,311
  • 21
  • 80
  • 127
Gus
  • 913
  • 2
  • 15
  • 30
  • 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 – Pranay Rana Jul 27 '15 at 07:23
  • Why do you need this functionality? – carloabelli Jul 27 '15 at 07:24
  • 2
    You can only have dynamic properties of objects (including the global object, `window`, if you like), but not local variables. – GregL Jul 27 '15 at 07: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 : ) – Manish Mishra Jul 27 '15 at 07:24
  • it is possible only if your variables are global or under some scope. – iamawebgeek Jul 27 '15 at 07:25
  • Why can't you use Arrays for you functionality... – answer99 Jul 27 '15 at 07:27
  • possible duplicate of http://stackoverflow.com/questions/22727711/javascript-dynamic-variable-names – Anand Jul 27 '15 at 07:29
  • [Look this answer please : Use dynamic variable names in JavaScript][1] [1]: http://stackoverflow.com/questions/5117127/use-dynamic-variable-names-in-javascript – devseo Jul 27 '15 at 07:29

3 Answers3

10

You can make dynamic variable using this way

window['varname'] = "test";

alert(varname);

Romnick Susa
  • 1,279
  • 13
  • 31
4

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

eval("foo_" + i + "='bar'")
Tariq
  • 2,853
  • 3
  • 22
  • 29
  • What reservations would those be? – ThickMiddleManager Jan 10 '20 at 19:30
  • 1
    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: https://stackoverflow.com/questions/197769/when-is-javascripts-eval-not-evil# – Tariq Jan 12 '20 at 08:31
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"]);
Nikhil Aggarwal
  • 28,197
  • 4
  • 43
  • 59