var foo = "bar" var bar = "realvalue";
Is it possible to print the value of bar
using foo
?
After a value is assigned to a variable using the assignment operator, you can assign the value of that variable to another variable using the assignment operator. var myVar; myVar = 5; var myNum; myNum = myVar; The above declares a myVar variable with no value, then assigns it the value 5 .
Command Window — To view the value of a variable in the Command Window, type the variable name. For the example, to see the value of a variable n , type n and press Enter. The Command Window displays the variable name and its value.
Here is some code: window. onload = function show(){ var x = 3; } function trig(){ alert(x); } trig();
Python will joyfully accept a variable by that name, but it requires that any variable being used must already be assigned. The act of assignment to a variable allocates the name and space for the variable to contain a value. We saw that we can assign a variable a numeric value as well as a string (text) value.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With