var foo = "bar"
var bar = "realvalue";
Is it possible to print the value of bar
using foo
?
Approach 1: global variable
var foo = "bar";
var bar = "realvalue";
alert(window[foo]);
OR
Approach 2: namespace
Divide your js to namespaces
var namespace = {
foo : "bar",
bar : "realvalue"
};
alert(namespace[namespace.foo]);
Yeah you can do something like this with eval
var foo = "bar";
var bar = "realvalue";
alert(eval(foo));
EDIT: Seems a lot of people are against using the eval() function. My advice before using it is read this question: Why is using the JavaScript eval function a bad idea?
Then once you understand the risks you can decide for yourself if you wish to use it.
eval
is evil is another thing, its a correct and valid answer
Commented
Dec 18, 2012 at 8:58
eval
command, this solution still has it's importance because it's good to know. In some cases you can't go without it...
If it's a global variable you can use window[foo]
Don't do this kind of constructs with non-global variables, just scope whatever variables you would otherwise have floating around.
var myscope = {
bar: 'realvalue'
},
foo = 'bar';
alert(myscope[foo]);
Btw, the above doesn't rely on the default behaviour of browsers to also register global variables in the window
object, making it work for things like Node.js too.
Global variables are defined on the window
object, so you can use:
var bar = "realvalue";
alert(window["bar"]);
Yes, via eval
. But unfortunately, not without eval
, which is a bad idea to use.
eval()
.