Rakesh Juyal
Rakesh Juyal

Reputation: 36759

How to display value of value of another variable?

var foo = "bar"
var bar  = "realvalue";

Is it possible to print the value of bar using foo ?

Upvotes: 31

Views: 1260

Answers (8)

user1331
user1331

Reputation: 38

 var foo = "bar";
 var bar  = "realvalue";
 alert(eval(foo));

Upvotes: 1

Ja͢ck
Ja͢ck

Reputation: 173572

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.

Upvotes: 10

cowls
cowls

Reputation: 24334

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.

Upvotes: 17

Akhil Sekharan
Akhil Sekharan

Reputation: 12683

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]);

Upvotes: 44

Balwinder Pal
Balwinder Pal

Reputation: 97

var foo = "bar";
var bar  = "realvalue";
foo=bar;
console.log(foo);
alert(foo);

Upvotes: 2

Moseleyi
Moseleyi

Reputation: 2859

If it's a global variable you can use window[foo]

Upvotes: 14

palaѕн
palaѕн

Reputation: 73906

Global variables are defined on the window object, so you can use:

var bar = "realvalue";
alert(window["bar"]);

Upvotes: 2

Kilian Foth
Kilian Foth

Reputation: 14346

Yes, via eval. But unfortunately, not without eval, which is a bad idea to use.

Upvotes: 0

Related Questions