Tuesday, August 13, 2019

 

Variable Variables in Javascript

In javascript, if the name of the variable you want is stored in another variable, one approach is to use "window[variableName]".

But beware - this ONLY works if the declaration was in a statement using "var", eg "var a=23;"
It does NOT work if you declare using "let" or "const".

Try this:
        const THIS_CONST=123;
        let constName="THIS_CONST";
        alert("const="+window[constName]);

        let THIS_LET=456;
        let letName="THIS_LET";
        alert("let="+window[letName]);


        var THIS_VARIABLE=789;
        let varName="THIS_VARIABLE";
        alert("var="+window[varName]);

So:
Variable variable - Yes
Variable let - No
Variable const - No

This page is powered by Blogger. Isn't yours?