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

1
  • Check my edit, please. Commented Aug 21, 2015 at 16:05

7 Answers 7

11

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

var MyVariable = "Value of variable";
alert(window["MyVariable"]);
Sign up to request clarification or add additional context in comments.

3 Comments

-1 You need to remove 'var' before MyVariable to make it a part of window object.
@craftsman : that is not true. All variables declared in the global scope are part of the window object.
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.
6

Yes, you can do it like this:

var MyVariable = "Value of variable";
alert(window["MyVariable"]);

4 Comments

This is correct, for those interested in learning more, it's called bracket notation.
That is a great link, Nick. Thanks for sharing!
..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)
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"]?
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)

2 Comments

End-of-lines (Carriage-Return) did not work in my answer. Sorry. Take care to reconstitute them.
Wouldn't the function need to be declared before you try to alert the returned value??
1
var sen0=1;
if(window["sen"+n] > 0){
}

Comments

1

Try this ^_^

var MyVariable = "Value of variable";

alert(readValue("MyVariable"));

function readValue(name) {
    return eval(name)
}

2 Comments

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.
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]];
}

Comments

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

1 Comment

I realize 'wrong' and 'correct' are misnomer. What I should say is: wrong: Not what I want and correct: What I want

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.