Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access value of JavaScript variable by name?

Tags:

javascript

Hello it is possible to access the value of a JavaScript variable by name? Example:

var MyVariable = "Value of variable";


function readValue(name) {
     ....
}


alert(readValue("MyVariable"));

Is this possible, so that the output is "Value of variable"? If yes, how do I write this function?

Thanks

like image 843
Torben Avatar asked Dec 09 '10 15:12

Torben


People also ask

How do you find the value of an object in a variable?

Use bracket notation to get an object's value by a variable key, e.g. obj[myVar] . The variable or expression in the brackets gets evaluated, so if a key with the computed name exists, you will get the corresponding value back.

What is difference between VAR and let?

var and let are both used for variable declaration in javascript but the difference between them is that var is function scoped and let is block scoped. Variable declared by let cannot be redeclared and must be declared before use whereas variables declared with var keyword are hoisted.

When to use let and VAR in JavaScript?

let allows you to declare variables that are limited to the scope of a block statement, or expression on which it is used, unlike the var keyword, which declares a variable globally, or locally to an entire function regardless of block scope.


2 Answers

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

var MyVariable = "Value of variable";
alert(window["MyVariable"]);
like image 112
Spiny Norman Avatar answered Sep 23 '22 00:09

Spiny Norman


Yes, you can do it like this:

var MyVariable = "Value of variable";
alert(window["MyVariable"]);
like image 38
wsanville Avatar answered Sep 22 '22 00:09

wsanville