Variable Variables in Javascript

Sometimes it is useful to use one variables value as the name for a new variable, in php this is pretty simple:

$name="bob";
$$name="My name is bob";
in php, the variable $bob now contains "My name is bob"

But what about javascript? Well, its actually pretty simple too – not quite as easy as php but easy nonetheless.

var name="bob";
window[name]="My name is bob";

The window[] associative array contains all the variables in your javascript program, so we can use this to add a new variable using the value of an old variable as the name.

To test it out just try a quick alert:

alert(bob);

You should get "My name is bob" in the alert box, letting you know that the "bob" variable is set.

You can also use this[] in place of window[] although I have not tried it more than once to test it – so you mileage may vary.