Take the 2-minute tour ×

I know it's possible in PHP to have "Variable" variables. For example $x = "variable"; $$x = "hello, world!"; echo $variable;"

Is this possible in javascript? How would it be done?

share|improve this question
No, it's generally not possible. Thank goodness. –  lonesomeday Mar 3 '11 at 22:42

9 Answers 9

up vote 49 down vote accepted


var obj = {}
obj.foo = 42;

var bar = 'foo';


share|improve this answer


var data = "testVariable";

Or using the window object:

var data = "testVariable";
window["temp_" + data] = 123;
alert(window["temp_" + data]);


share|improve this answer


var killingFunction = 'alert'
var killMeNow = 'please'
var please = 'You have been killed!'
share|improve this answer


share|improve this answer
var vars = {};
var var_name = "str";
vars[var_name] = "working";
share|improve this answer




share|improve this answer


share|improve this answer


var myvars = {};
myvars.foo = "hello, world!";


It even works with functions:


You can do the same with arrays. So:

var myarr = [];
myarr.push("hello, world!");

share|improve this answer


share|improve this answer

Your Answer


