11

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

Sean Kendle
  • 3,538
  • 1
  • 27
  • 34
Torben
  • 1,290
  • 5
  • 22
  • 41

7 Answers7

11

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

var MyVariable = "Value of variable";
alert(window["MyVariable"]);
Spiny Norman
  • 8,277
  • 1
  • 30
  • 55
  • -1 You need to remove 'var' before MyVariable to make it a part of window object. – craftsman Jul 19 '12 at 11:04
  • 2
    @craftsman : that is not true. All variables declared in the global scope are part of the window object. – Brian McCutchon Aug 07 '13 at 20:37
  • 3
    why do people mark these answers as correct? It's only correct if everything in OP is in the global context. The correct answer either needs the addition of a "context" object or to fix a poor design. – Lance Caraccioli Mar 29 '14 at 09:14
6

Yes, you can do it like this:

var MyVariable = "Value of variable";
alert(window["MyVariable"]);
wsanville
  • 37,158
  • 8
  • 76
  • 101
  • 1
    This is correct, for those interested in learning more, it's called [bracket notation](https://developer.mozilla.org/en/JavaScript/Reference/Operators/Member_Operators). – Nick Craver Dec 09 '10 at 15:25
  • That is a great link, Nick. Thanks for sharing! – wsanville Dec 09 '10 at 15:27
  • 1
    ..and the reason why you're using window[] is because MyVariable is in global scope which makes it a property of the `window` object. (`window` object is the global object in client side JS) – instantsetsuna Dec 09 '10 at 15:39
  • Can you do that with a variable declared in another scope? Like, if I declared a variable in a function `testFunc(){ var testVar }` could I access that with `testFunc["testVar"]`? – Sean Kendle Aug 21 '15 at 16:11
3
var MyVariable = "Value of variable";    
alert(readValue("MyVariable"));    

// function readEValue(name) { readevalue -> readvalue // always do copy-paste to avoid errors  
function readValue(name) {   
 return window[name]   
}   

That's all about ;o)

Mike Zboray
  • 39,828
  • 3
  • 90
  • 122
1
var sen0=1;
if(window["sen"+n] > 0){
}
Jesus Ramos
  • 22,940
  • 10
  • 58
  • 88
lyon819
  • 89
  • 1
  • 2
0

Try this ^_^

var MyVariable = "Value of variable";

alert(readValue("MyVariable"));

function readValue(name) {
    return eval(name)
}
dsh
  • 12,037
  • 3
  • 33
  • 51
shunz19
  • 495
  • 4
  • 13
  • [Why using the JavaScript eval function is a bad idea](http://stackoverflow.com/a/86580/1172714) – dsh Aug 21 '15 at 16:46
  • If you hard-code the string then you can verify that it is safe ... or just remove the quotes and use the name normally. If the name of the variable is in a string then I am very certain that it will come from somewhere external (AJAX response, database contents, etc.) which can not be audited for safety. – dsh Aug 22 '15 at 13:37
0

I tried the function below which was posted by Nicolas Gauthier via Stack Overflow to get a function from a string by naming it, and when used with the name of a variable, it returns the variable's value.

It copes with dotted variable names (values of an object). It works with global variables and variables declared with var, but NOT with variables defined with 'let' which are not visible in called functions.

/***
 * getFunctionFromString - Get function from string
 *
 * works with or without scopes
 *
 * @param  string   string  name of function
 * @return function         by that name if it exists
 * @author by Nicolas Gauthier via Stack Overflow
 ***/
window.getFunctionFromString = function(string)
{
    let scope = window; let x=parent;
    let scopeSplit = string.split('.');
    let i;

    for (i = 0; i < scopeSplit.length - 1; i++)
    {
        scope = scope[scopeSplit[i]];

        if (scope == undefined) return;
    }

    return scope[scopeSplit[scopeSplit.length - 1]];
}
Chris Jeffries
  • 117
  • 2
  • 6
0
//Ran into this today

//Not what I want
var test = 'someString';
var data = [];
data.push({test:'001'});
console.log(test); --> 'someString';
console.log(data); --> 
 (1) [{…}] 
    0: {test: "001"}        //wrong


//Solution
var obj = {};
obj[test] = '001';
data.push(obj);
console.log(data); -->
(2) [{…}, {…}]
    0: {test: "001"}        //wrong
    1: {someString: "001"}  //correct
ssoward
  • 540
  • 5
  • 9
  • I realize 'wrong' and 'correct' are misnomer. What I should say is: wrong: Not what I want and correct: What I want – ssoward Oct 05 '18 at 18:57