Use dynamic variable names in JavaScriptJavascript - set a variable using concatenation of stringsUsing string as variable name in JS?Create a new unique global variable each time a function is run in javascriptConcatenation in variable namesDynamic array names in jQueryHow to concatenate variable inside function name?How to put variable value inside another variable name in JavascriptCreate dynamic arrays using for loop with jquery/javascript can not access outside or cant access globalcreate variable name functionJavaScript have a variable in a variable nameHow do JavaScript closures work?How do I remove a property from a JavaScript object?Which equals operator (== vs ===) should be used in JavaScript comparisons?How do you check if a variable is an array in JavaScript?Set a default parameter value for a JavaScript functionHow do I include a JavaScript file in another JavaScript file?What does “use strict” do in JavaScript, and what is the reasoning behind it?How to check whether a string contains a substring in JavaScript?How to decide when to use Node.js?How do I remove a particular element from an array in JavaScript?

Remove color cast in darktable?

spatiotemporal regression

Why is it wrong to *implement* myself a known, published, widely believed to be secure crypto algorithm?

Why should password hash verification be time consistent?

date -d 'previous Monday" to display the preceding Monday

How is CoreiX like Corei5, i7 is related to Haswell, Ivy Bridge?

Can a surprised creature fall prone voluntarily on their turn?

Whats the purpose of lockedLoadData / uncached page build takes around a minute, spent in usleep

Electric kick drum pedal starts oscillating in such a way that it does not register hits

Translation of the latin word 'sit' in Thomas Aquinas' works

Best species to breed to intelligence

Has magnetic core memory been used beyond the Moon?

Why does increasing the sampling rate make implementing an anti-aliasing filter easier?

My perfect evil overlord plan... or is it?

What does formal training in a field mean?

Is there any evidence that democracy is linked causatively with improved outcomes?

Would encrypting a database protect against a compromised admin account?

When do you stop "pushing" a book?

Why did Captain America age?

What's the "magic similar to the Knock spell" referenced in the Dungeon of the Mad Mage adventure?

Is a vertical stabiliser needed for straight line flight in a glider?

A Cunning Riley Riddle

How did Arya survive this confrontation unscathed?

What is the name of meteoroids which hit Moon, Mars, or pretty much anything that isn’t the Earth?



Use dynamic variable names in JavaScript


Javascript - set a variable using concatenation of stringsUsing string as variable name in JS?Create a new unique global variable each time a function is run in javascriptConcatenation in variable namesDynamic array names in jQueryHow to concatenate variable inside function name?How to put variable value inside another variable name in JavascriptCreate dynamic arrays using for loop with jquery/javascript can not access outside or cant access globalcreate variable name functionJavaScript have a variable in a variable nameHow do JavaScript closures work?How do I remove a property from a JavaScript object?Which equals operator (== vs ===) should be used in JavaScript comparisons?How do you check if a variable is an array in JavaScript?Set a default parameter value for a JavaScript functionHow do I include a JavaScript file in another JavaScript file?What does “use strict” do in JavaScript, and what is the reasoning behind it?How to check whether a string contains a substring in JavaScript?How to decide when to use Node.js?How do I remove a particular element from an array in JavaScript?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








304















In PHP you can do amazing/horrendous things like this:



$a = 1;
$b = 2;
$c = 3;
$name = 'a';
echo $$name;
// prints 1


Is there any way of doing something like this with Javascript?



E.g. if I have a var name = 'the name of the variable'; can I get a reference to the variable with name name?










share|improve this question



















  • 2





    Possible dupe of stackoverflow.com/questions/724857/…, and stackoverflow.com/questions/1664282/…, but the accepted answer here better, IMO.

    – goodeye
    May 22 '13 at 22:41

















304















In PHP you can do amazing/horrendous things like this:



$a = 1;
$b = 2;
$c = 3;
$name = 'a';
echo $$name;
// prints 1


Is there any way of doing something like this with Javascript?



E.g. if I have a var name = 'the name of the variable'; can I get a reference to the variable with name name?










share|improve this question



















  • 2





    Possible dupe of stackoverflow.com/questions/724857/…, and stackoverflow.com/questions/1664282/…, but the accepted answer here better, IMO.

    – goodeye
    May 22 '13 at 22:41













304












304








304


86






In PHP you can do amazing/horrendous things like this:



$a = 1;
$b = 2;
$c = 3;
$name = 'a';
echo $$name;
// prints 1


Is there any way of doing something like this with Javascript?



E.g. if I have a var name = 'the name of the variable'; can I get a reference to the variable with name name?










share|improve this question
















In PHP you can do amazing/horrendous things like this:



$a = 1;
$b = 2;
$c = 3;
$name = 'a';
echo $$name;
// prints 1


Is there any way of doing something like this with Javascript?



E.g. if I have a var name = 'the name of the variable'; can I get a reference to the variable with name name?







javascript dynamic-variables






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Aug 29 '14 at 5:38









user2864740

44.6k674151




44.6k674151










asked Feb 25 '11 at 12:19









FinbarrFinbarr

20k95484




20k95484







  • 2





    Possible dupe of stackoverflow.com/questions/724857/…, and stackoverflow.com/questions/1664282/…, but the accepted answer here better, IMO.

    – goodeye
    May 22 '13 at 22:41












  • 2





    Possible dupe of stackoverflow.com/questions/724857/…, and stackoverflow.com/questions/1664282/…, but the accepted answer here better, IMO.

    – goodeye
    May 22 '13 at 22:41







2




2





Possible dupe of stackoverflow.com/questions/724857/…, and stackoverflow.com/questions/1664282/…, but the accepted answer here better, IMO.

– goodeye
May 22 '13 at 22:41





Possible dupe of stackoverflow.com/questions/724857/…, and stackoverflow.com/questions/1664282/…, but the accepted answer here better, IMO.

– goodeye
May 22 '13 at 22:41












14 Answers
14






active

oldest

votes


















313














Since ECMA-/Javascript is all about Objects and Contexts (which, are also somekind of Object), every variable is stored in a such called Variable- (or in case of a Function, Activation Object).



So if you create variables like this:



var a = 1,
b = 2,
c = 3;


In the Global scope (= NO function context), you implicitly write those variables into the Global object (= window in a browser).



Those can get accessed by using the "dot" or "bracket" notation:



var name = window.a;


or



var name = window['a'];


This only works for the global object in this particular instance, because the Variable Object of the Global Object is the window object itself. Within the Context of a function, you don't have direct access to the Activation Object. For instance:



function foobar() 
this.a = 1;
this.b = 2;

var name = window['a']; // === undefined
alert(name);
name = this['a']; // === 1
alert(name);


new foobar();


new creates a new instance of a self-defined object (context). Without new the scope of the function would be also global (=window). This example would alert undefined and 1 respectively. If we would replace this.a = 1; this.b = 2 with:



var a = 1,
b = 2;


Both alert outputs would be undefined. In that scenario, the variables a and b would get stored in the Activation Object from foobar, which we cannot access (of course we could access those directly by calling a and b).






share|improve this answer




















  • 1





    Another cool thing is that in this way you can add callback (start/end) for any global level function.

    – antitoxic
    Aug 7 '12 at 7:39






  • 4





    But what if my dynamic variable is local in a function? for example: function boink() var a = 1; // this will not work var dynamic = this['a']; // this also wont work var dynamic = ['a'];

    – Kokodoko
    Oct 28 '13 at 11:03












  • @Kokodoko—because this isn't "context" or a reference to a function's execution context (there is no way to reference an execution context, it's forbidden by the ECMA-262). this is set by how a function is called (or by bind), it's just an Object that has nothing to do with the execution context in which it's accessible.

    – RobG
    May 13 '15 at 2:55











  • If you need to access nested properties check out stackoverflow.com/questions/4244896/…

    – Mr Br
    Jun 22 '15 at 8:12











  • pointed me in the right direction with the bracket notation. Was stuck thinking dot notation only.

    – Andrew
    Mar 2 '17 at 20:29


















141














eval is one option.



var a = 1;
var name = 'a';

document.write(eval(name)); // 1





share|improve this answer


















  • 10





    No it shouldn't as eval is evil. Never use eval!

    – EasyBB
    Jan 18 '14 at 21:18






  • 35





    @EasyBB - if you're going to say never to use something, I't helpful to explain why. I have a situation in which I can't think of any other way to accomplish what I'm doing other than eval()

    – Rampant Creative Group
    Mar 25 '14 at 10:54






  • 2





    Eval poses a risk for attacks on end users and we'll it's not technically evil rather misunderstood and misused in a lost of cases. I've seen php responses which hold literal vars in it then use eval to run it. Though this shouldn't be used in this case as there are better methods. This question at hand eval should not be used at all as there are better methods overall and I'm sure a lot of us know this.

    – EasyBB
    Mar 25 '14 at 13:26






  • 2





    Via javascriptweblog.wordpress.com/2010/04/19/how-evil-is-eval --- "Let’s consider the arguments most frequently leveled against using eval: 1) It requires a compile and is therefore slow 2) What if a malicious script found its way into the eval argument? 3) It looks ugly 4) It inherits the execution context and this binding of the scope in which its invoked"

    – mattLummus
    May 13 '15 at 15:07







  • 1





    Here is how to create dynamic variables using eval: stackoverflow.com/a/13291766/5528600

    – am2124429
    Mar 21 '16 at 12:54


















69














You can use the window object to get at it .



window['myVar']


window has a reference to all global variables and global functions you are using.






share|improve this answer




















  • 24





    And needless to say, this one is safer than eval().

    – Cray
    Feb 25 '11 at 12:23


















34














Just don't know what a bad answer gets so many votes. It's quite easy answer but you make it complex.



// If you want to get article_count
// var article_count = 1000;
var type = 'article';
this[type+'_count'] = 1000; // in a function we use "this";
alert(article_count);





share|improve this answer




















  • 9





    "in a function we use this" - If you want to access a global variable in this way, it is better to be explicit and use the window object, not this. this is ambiguous.

    – MrWhite
    Aug 23 '15 at 23:25


















27














a = 'varname';
str = a+' = '+'123';
eval(str)
alert(varname);


Try this...






share|improve this answer






























    23














    This is an example :



    for(var i=0; i<=3; i++) 
    window['p'+i] = "hello " + i;


    alert(p0); // hello 0
    alert(p1); // hello 1
    alert(p2); // hello 2
    alert(p3); // hello 3


    Another example :



    var myVariable = 'coco';
    window[myVariable] = 'riko';

    alert(coco); // display : riko


    So, the value "coco" of myVariable becomes a variable coco.



    Because all the variables in the global scope are properties of the Window object.






    share|improve this answer
































      12














      In Javascript you can use the fact that all properties are key value pairs. jAndy already mentioned this but I don't think his answer show how it can be exploited.



      Usually you are not trying to create a variable to hold a variable name but are trying to generate variable names and then use them. PHP does it with $$var notation but Javascript doesn't need to because property keys are interchangeable with array keys.



      var id = "abc";
      var mine = ;
      mine[id] = 123;
      console.log(mine.abc);


      gives 123. Usually you want to construct the variable which is why there is the indirection so you can also do it the other way around.



      var mine = ;
      mine.abc = 123;
      console.log(mine["a"+"bc"]);





      share|improve this answer


















      • 1





        var someJsonObj = ; in a loop.... for(var i=0; i<=3; i++) someJsonObj[i] = []; , but i can be anything. so dynamically generated variables, all sit inside someJsonObj for easy reference.

        – rajeev
        Apr 7 '17 at 6:31



















      4














      If you don't want to use a global object like window or global (node), you can try something like this:



      var obj = ;
      obj['whatever'] = 'There's no need to store even more stuff in a global object.';

      console.log(obj['whatever']);





      share|improve this answer






























        2














        I needed to draw multiple FormData on the fly and object way worked well



        var forms = 


        Then in my loops whereever i needed to create a form data i used



        forms["formdata"+counter]=new FormData();
        forms["formdata"+counter].append(var_name, var_value);





        share|improve this answer






























          2














          2019



          TL;DR




          • eval operator can run string expression in the context it called and return the value, also variables;


          • literal object theoretically can do that [varName], but it blocked by definition.

          So I come across this question and everyone here just play around without bringing a real solution. Thanks to @Axel Heider, who was approaching.



          The right solution is eval



          The almost most forgotten language operator. ( I think the most one is with )



          so reserve word operator eval can dynamically run expression in the context it called. and return the result of that expression. we can use that to dynamicly return a value of a variable in a function context.



          example:



          function exmaple1()
          var a = 1, b = 2, default = 3;
          var name = 'a';
          return eval(name)


          example1() // return 1


          function example2(option)
          var a = 1, b = 2, defaultValue = 3;

          switch(option)
          case 'a': name = 'a'; break;
          case 'b': name = 'b'; break;
          default: name = 'defaultValue';

          return eval (name);


          example2('a') // return 1
          example2('b') // return 2
          example2() // return 3


          Note that I always write explicitly the expression eval will run.
          To avoid unnecessary surprises in the code. eval is very strong

          But I'm sure you know that already



          BTW, if it was legal we could use literal object to capture the variable name and value, but we can’t combine computed property names and property value shorthand, sadly, is invalid



          functopn example( varName )
          var var1 = 'foo', var2 ='bar'

          var capture = [varName]



          example('var1') //trow 'Uncaught SyntaxError: Unexpected token }`





          share|improve this answer
































            1














            what they mean is no, you can't.
            there is no way to get it done.
            so it was possible you could do something like this



            function create(obj, const)
            // where obj is an object and const is a variable name
            function const ()

            const.prototype.myProperty = property_value;
            // .. more prototype

            return new const();




            having a create function just like the one implemented in ECMAScript 5.






            share|improve this answer


















            • 4





              Beware: const is a keyword in ES6

              – Tejas Manohar
              Nov 17 '15 at 9:00






            • 4





              ...and prior to that was a future reserved word.

              – T.J. Crowder
              Dec 9 '15 at 16:23











            • there is eval operator

              – pery mimon
              Jan 5 at 9:46


















            1














            eval() did not work in my tests. But adding new JavaScript code to the DOM tree is possible. So here is a function that adds a new variable:



            function createVariable(varName,varContent)

            var scriptStr = "var "+varName+"= ""+varContent+"""

            var node_scriptCode = document.createTextNode( scriptStr )
            var node_script = document.createElement("script");
            node_script.type = "text/javascript"
            node_script.appendChild(node_scriptCode);

            var node_head = document.getElementsByTagName("head")[0]
            node_head.appendChild(node_script);


            createVariable("dynamicVar", "some content")
            console.log(dynamicVar)





            share|improve this answer




















            • 2





              small improvement, it is better to use var node_head = document.getElementsByTagName("head")[0] instead of ID, as no one gives an id="head" to <head> :-)

              – ddlab
              Nov 9 '14 at 17:41











            • I do :) But thanks, now I can finally remove this `id="head" thing

              – Axel Heider
              May 4 '15 at 11:33







            • 1





              This just seems to be an overly complex way of creating a global variable?! (...and how does this answer the question?)

              – MrWhite
              Aug 23 '15 at 23:39











            • genius :) eval is the solution. Even if your code does not work

              – pery mimon
              Jan 4 at 18:27


















            0














            use Object is great too.



            var a=123
            var b=234
            var temp = "a":a,"b":b
            console.log(temp["a"],temp["b"]);





            share|improve this answer






























              0














              Although this have an accepted answer I would like to add an observation:



              In ES6 using let doesn't work:






              /*this is NOT working*/
              let t = "skyBlue",
              m = "gold",
              b = "tomato";

              let color = window["b"];
              console.log(color);





              However using var works






              /*this IS working*/
              var t = "skyBlue",
              m = "gold",
              b = "tomato";

              let color = window["b"];
              console.log(color);





              I hope this may be useful to some.






              share|improve this answer


















              • 1





                same applies to const

                – user4244405
                Apr 19 at 8:26









              protected by Community Apr 11 '18 at 16:47



              Thank you for your interest in this question.
              Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



              Would you like to answer one of these unanswered questions instead?














              14 Answers
              14






              active

              oldest

              votes








              14 Answers
              14






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              313














              Since ECMA-/Javascript is all about Objects and Contexts (which, are also somekind of Object), every variable is stored in a such called Variable- (or in case of a Function, Activation Object).



              So if you create variables like this:



              var a = 1,
              b = 2,
              c = 3;


              In the Global scope (= NO function context), you implicitly write those variables into the Global object (= window in a browser).



              Those can get accessed by using the "dot" or "bracket" notation:



              var name = window.a;


              or



              var name = window['a'];


              This only works for the global object in this particular instance, because the Variable Object of the Global Object is the window object itself. Within the Context of a function, you don't have direct access to the Activation Object. For instance:



              function foobar() 
              this.a = 1;
              this.b = 2;

              var name = window['a']; // === undefined
              alert(name);
              name = this['a']; // === 1
              alert(name);


              new foobar();


              new creates a new instance of a self-defined object (context). Without new the scope of the function would be also global (=window). This example would alert undefined and 1 respectively. If we would replace this.a = 1; this.b = 2 with:



              var a = 1,
              b = 2;


              Both alert outputs would be undefined. In that scenario, the variables a and b would get stored in the Activation Object from foobar, which we cannot access (of course we could access those directly by calling a and b).






              share|improve this answer




















              • 1





                Another cool thing is that in this way you can add callback (start/end) for any global level function.

                – antitoxic
                Aug 7 '12 at 7:39






              • 4





                But what if my dynamic variable is local in a function? for example: function boink() var a = 1; // this will not work var dynamic = this['a']; // this also wont work var dynamic = ['a'];

                – Kokodoko
                Oct 28 '13 at 11:03












              • @Kokodoko—because this isn't "context" or a reference to a function's execution context (there is no way to reference an execution context, it's forbidden by the ECMA-262). this is set by how a function is called (or by bind), it's just an Object that has nothing to do with the execution context in which it's accessible.

                – RobG
                May 13 '15 at 2:55











              • If you need to access nested properties check out stackoverflow.com/questions/4244896/…

                – Mr Br
                Jun 22 '15 at 8:12











              • pointed me in the right direction with the bracket notation. Was stuck thinking dot notation only.

                – Andrew
                Mar 2 '17 at 20:29















              313














              Since ECMA-/Javascript is all about Objects and Contexts (which, are also somekind of Object), every variable is stored in a such called Variable- (or in case of a Function, Activation Object).



              So if you create variables like this:



              var a = 1,
              b = 2,
              c = 3;


              In the Global scope (= NO function context), you implicitly write those variables into the Global object (= window in a browser).



              Those can get accessed by using the "dot" or "bracket" notation:



              var name = window.a;


              or



              var name = window['a'];


              This only works for the global object in this particular instance, because the Variable Object of the Global Object is the window object itself. Within the Context of a function, you don't have direct access to the Activation Object. For instance:



              function foobar() 
              this.a = 1;
              this.b = 2;

              var name = window['a']; // === undefined
              alert(name);
              name = this['a']; // === 1
              alert(name);


              new foobar();


              new creates a new instance of a self-defined object (context). Without new the scope of the function would be also global (=window). This example would alert undefined and 1 respectively. If we would replace this.a = 1; this.b = 2 with:



              var a = 1,
              b = 2;


              Both alert outputs would be undefined. In that scenario, the variables a and b would get stored in the Activation Object from foobar, which we cannot access (of course we could access those directly by calling a and b).






              share|improve this answer




















              • 1





                Another cool thing is that in this way you can add callback (start/end) for any global level function.

                – antitoxic
                Aug 7 '12 at 7:39






              • 4





                But what if my dynamic variable is local in a function? for example: function boink() var a = 1; // this will not work var dynamic = this['a']; // this also wont work var dynamic = ['a'];

                – Kokodoko
                Oct 28 '13 at 11:03












              • @Kokodoko—because this isn't "context" or a reference to a function's execution context (there is no way to reference an execution context, it's forbidden by the ECMA-262). this is set by how a function is called (or by bind), it's just an Object that has nothing to do with the execution context in which it's accessible.

                – RobG
                May 13 '15 at 2:55











              • If you need to access nested properties check out stackoverflow.com/questions/4244896/…

                – Mr Br
                Jun 22 '15 at 8:12











              • pointed me in the right direction with the bracket notation. Was stuck thinking dot notation only.

                – Andrew
                Mar 2 '17 at 20:29













              313












              313








              313







              Since ECMA-/Javascript is all about Objects and Contexts (which, are also somekind of Object), every variable is stored in a such called Variable- (or in case of a Function, Activation Object).



              So if you create variables like this:



              var a = 1,
              b = 2,
              c = 3;


              In the Global scope (= NO function context), you implicitly write those variables into the Global object (= window in a browser).



              Those can get accessed by using the "dot" or "bracket" notation:



              var name = window.a;


              or



              var name = window['a'];


              This only works for the global object in this particular instance, because the Variable Object of the Global Object is the window object itself. Within the Context of a function, you don't have direct access to the Activation Object. For instance:



              function foobar() 
              this.a = 1;
              this.b = 2;

              var name = window['a']; // === undefined
              alert(name);
              name = this['a']; // === 1
              alert(name);


              new foobar();


              new creates a new instance of a self-defined object (context). Without new the scope of the function would be also global (=window). This example would alert undefined and 1 respectively. If we would replace this.a = 1; this.b = 2 with:



              var a = 1,
              b = 2;


              Both alert outputs would be undefined. In that scenario, the variables a and b would get stored in the Activation Object from foobar, which we cannot access (of course we could access those directly by calling a and b).






              share|improve this answer















              Since ECMA-/Javascript is all about Objects and Contexts (which, are also somekind of Object), every variable is stored in a such called Variable- (or in case of a Function, Activation Object).



              So if you create variables like this:



              var a = 1,
              b = 2,
              c = 3;


              In the Global scope (= NO function context), you implicitly write those variables into the Global object (= window in a browser).



              Those can get accessed by using the "dot" or "bracket" notation:



              var name = window.a;


              or



              var name = window['a'];


              This only works for the global object in this particular instance, because the Variable Object of the Global Object is the window object itself. Within the Context of a function, you don't have direct access to the Activation Object. For instance:



              function foobar() 
              this.a = 1;
              this.b = 2;

              var name = window['a']; // === undefined
              alert(name);
              name = this['a']; // === 1
              alert(name);


              new foobar();


              new creates a new instance of a self-defined object (context). Without new the scope of the function would be also global (=window). This example would alert undefined and 1 respectively. If we would replace this.a = 1; this.b = 2 with:



              var a = 1,
              b = 2;


              Both alert outputs would be undefined. In that scenario, the variables a and b would get stored in the Activation Object from foobar, which we cannot access (of course we could access those directly by calling a and b).







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Dec 2 '12 at 23:54









              McGarnagle

              87.3k24190233




              87.3k24190233










              answered Feb 25 '11 at 12:23









              jAndyjAndy

              179k43268330




              179k43268330







              • 1





                Another cool thing is that in this way you can add callback (start/end) for any global level function.

                – antitoxic
                Aug 7 '12 at 7:39






              • 4





                But what if my dynamic variable is local in a function? for example: function boink() var a = 1; // this will not work var dynamic = this['a']; // this also wont work var dynamic = ['a'];

                – Kokodoko
                Oct 28 '13 at 11:03












              • @Kokodoko—because this isn't "context" or a reference to a function's execution context (there is no way to reference an execution context, it's forbidden by the ECMA-262). this is set by how a function is called (or by bind), it's just an Object that has nothing to do with the execution context in which it's accessible.

                – RobG
                May 13 '15 at 2:55











              • If you need to access nested properties check out stackoverflow.com/questions/4244896/…

                – Mr Br
                Jun 22 '15 at 8:12











              • pointed me in the right direction with the bracket notation. Was stuck thinking dot notation only.

                – Andrew
                Mar 2 '17 at 20:29












              • 1





                Another cool thing is that in this way you can add callback (start/end) for any global level function.

                – antitoxic
                Aug 7 '12 at 7:39






              • 4





                But what if my dynamic variable is local in a function? for example: function boink() var a = 1; // this will not work var dynamic = this['a']; // this also wont work var dynamic = ['a'];

                – Kokodoko
                Oct 28 '13 at 11:03












              • @Kokodoko—because this isn't "context" or a reference to a function's execution context (there is no way to reference an execution context, it's forbidden by the ECMA-262). this is set by how a function is called (or by bind), it's just an Object that has nothing to do with the execution context in which it's accessible.

                – RobG
                May 13 '15 at 2:55











              • If you need to access nested properties check out stackoverflow.com/questions/4244896/…

                – Mr Br
                Jun 22 '15 at 8:12











              • pointed me in the right direction with the bracket notation. Was stuck thinking dot notation only.

                – Andrew
                Mar 2 '17 at 20:29







              1




              1





              Another cool thing is that in this way you can add callback (start/end) for any global level function.

              – antitoxic
              Aug 7 '12 at 7:39





              Another cool thing is that in this way you can add callback (start/end) for any global level function.

              – antitoxic
              Aug 7 '12 at 7:39




              4




              4





              But what if my dynamic variable is local in a function? for example: function boink() var a = 1; // this will not work var dynamic = this['a']; // this also wont work var dynamic = ['a'];

              – Kokodoko
              Oct 28 '13 at 11:03






              But what if my dynamic variable is local in a function? for example: function boink() var a = 1; // this will not work var dynamic = this['a']; // this also wont work var dynamic = ['a'];

              – Kokodoko
              Oct 28 '13 at 11:03














              @Kokodoko—because this isn't "context" or a reference to a function's execution context (there is no way to reference an execution context, it's forbidden by the ECMA-262). this is set by how a function is called (or by bind), it's just an Object that has nothing to do with the execution context in which it's accessible.

              – RobG
              May 13 '15 at 2:55





              @Kokodoko—because this isn't "context" or a reference to a function's execution context (there is no way to reference an execution context, it's forbidden by the ECMA-262). this is set by how a function is called (or by bind), it's just an Object that has nothing to do with the execution context in which it's accessible.

              – RobG
              May 13 '15 at 2:55













              If you need to access nested properties check out stackoverflow.com/questions/4244896/…

              – Mr Br
              Jun 22 '15 at 8:12





              If you need to access nested properties check out stackoverflow.com/questions/4244896/…

              – Mr Br
              Jun 22 '15 at 8:12













              pointed me in the right direction with the bracket notation. Was stuck thinking dot notation only.

              – Andrew
              Mar 2 '17 at 20:29





              pointed me in the right direction with the bracket notation. Was stuck thinking dot notation only.

              – Andrew
              Mar 2 '17 at 20:29













              141














              eval is one option.



              var a = 1;
              var name = 'a';

              document.write(eval(name)); // 1





              share|improve this answer


















              • 10





                No it shouldn't as eval is evil. Never use eval!

                – EasyBB
                Jan 18 '14 at 21:18






              • 35





                @EasyBB - if you're going to say never to use something, I't helpful to explain why. I have a situation in which I can't think of any other way to accomplish what I'm doing other than eval()

                – Rampant Creative Group
                Mar 25 '14 at 10:54






              • 2





                Eval poses a risk for attacks on end users and we'll it's not technically evil rather misunderstood and misused in a lost of cases. I've seen php responses which hold literal vars in it then use eval to run it. Though this shouldn't be used in this case as there are better methods. This question at hand eval should not be used at all as there are better methods overall and I'm sure a lot of us know this.

                – EasyBB
                Mar 25 '14 at 13:26






              • 2





                Via javascriptweblog.wordpress.com/2010/04/19/how-evil-is-eval --- "Let’s consider the arguments most frequently leveled against using eval: 1) It requires a compile and is therefore slow 2) What if a malicious script found its way into the eval argument? 3) It looks ugly 4) It inherits the execution context and this binding of the scope in which its invoked"

                – mattLummus
                May 13 '15 at 15:07







              • 1





                Here is how to create dynamic variables using eval: stackoverflow.com/a/13291766/5528600

                – am2124429
                Mar 21 '16 at 12:54















              141














              eval is one option.



              var a = 1;
              var name = 'a';

              document.write(eval(name)); // 1





              share|improve this answer


















              • 10





                No it shouldn't as eval is evil. Never use eval!

                – EasyBB
                Jan 18 '14 at 21:18






              • 35





                @EasyBB - if you're going to say never to use something, I't helpful to explain why. I have a situation in which I can't think of any other way to accomplish what I'm doing other than eval()

                – Rampant Creative Group
                Mar 25 '14 at 10:54






              • 2





                Eval poses a risk for attacks on end users and we'll it's not technically evil rather misunderstood and misused in a lost of cases. I've seen php responses which hold literal vars in it then use eval to run it. Though this shouldn't be used in this case as there are better methods. This question at hand eval should not be used at all as there are better methods overall and I'm sure a lot of us know this.

                – EasyBB
                Mar 25 '14 at 13:26






              • 2





                Via javascriptweblog.wordpress.com/2010/04/19/how-evil-is-eval --- "Let’s consider the arguments most frequently leveled against using eval: 1) It requires a compile and is therefore slow 2) What if a malicious script found its way into the eval argument? 3) It looks ugly 4) It inherits the execution context and this binding of the scope in which its invoked"

                – mattLummus
                May 13 '15 at 15:07







              • 1





                Here is how to create dynamic variables using eval: stackoverflow.com/a/13291766/5528600

                – am2124429
                Mar 21 '16 at 12:54













              141












              141








              141







              eval is one option.



              var a = 1;
              var name = 'a';

              document.write(eval(name)); // 1





              share|improve this answer













              eval is one option.



              var a = 1;
              var name = 'a';

              document.write(eval(name)); // 1






              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Feb 25 '11 at 12:22









              erickberickb

              4,82621919




              4,82621919







              • 10





                No it shouldn't as eval is evil. Never use eval!

                – EasyBB
                Jan 18 '14 at 21:18






              • 35





                @EasyBB - if you're going to say never to use something, I't helpful to explain why. I have a situation in which I can't think of any other way to accomplish what I'm doing other than eval()

                – Rampant Creative Group
                Mar 25 '14 at 10:54






              • 2





                Eval poses a risk for attacks on end users and we'll it's not technically evil rather misunderstood and misused in a lost of cases. I've seen php responses which hold literal vars in it then use eval to run it. Though this shouldn't be used in this case as there are better methods. This question at hand eval should not be used at all as there are better methods overall and I'm sure a lot of us know this.

                – EasyBB
                Mar 25 '14 at 13:26






              • 2





                Via javascriptweblog.wordpress.com/2010/04/19/how-evil-is-eval --- "Let’s consider the arguments most frequently leveled against using eval: 1) It requires a compile and is therefore slow 2) What if a malicious script found its way into the eval argument? 3) It looks ugly 4) It inherits the execution context and this binding of the scope in which its invoked"

                – mattLummus
                May 13 '15 at 15:07







              • 1





                Here is how to create dynamic variables using eval: stackoverflow.com/a/13291766/5528600

                – am2124429
                Mar 21 '16 at 12:54












              • 10





                No it shouldn't as eval is evil. Never use eval!

                – EasyBB
                Jan 18 '14 at 21:18






              • 35





                @EasyBB - if you're going to say never to use something, I't helpful to explain why. I have a situation in which I can't think of any other way to accomplish what I'm doing other than eval()

                – Rampant Creative Group
                Mar 25 '14 at 10:54






              • 2





                Eval poses a risk for attacks on end users and we'll it's not technically evil rather misunderstood and misused in a lost of cases. I've seen php responses which hold literal vars in it then use eval to run it. Though this shouldn't be used in this case as there are better methods. This question at hand eval should not be used at all as there are better methods overall and I'm sure a lot of us know this.

                – EasyBB
                Mar 25 '14 at 13:26






              • 2





                Via javascriptweblog.wordpress.com/2010/04/19/how-evil-is-eval --- "Let’s consider the arguments most frequently leveled against using eval: 1) It requires a compile and is therefore slow 2) What if a malicious script found its way into the eval argument? 3) It looks ugly 4) It inherits the execution context and this binding of the scope in which its invoked"

                – mattLummus
                May 13 '15 at 15:07







              • 1





                Here is how to create dynamic variables using eval: stackoverflow.com/a/13291766/5528600

                – am2124429
                Mar 21 '16 at 12:54







              10




              10





              No it shouldn't as eval is evil. Never use eval!

              – EasyBB
              Jan 18 '14 at 21:18





              No it shouldn't as eval is evil. Never use eval!

              – EasyBB
              Jan 18 '14 at 21:18




              35




              35





              @EasyBB - if you're going to say never to use something, I't helpful to explain why. I have a situation in which I can't think of any other way to accomplish what I'm doing other than eval()

              – Rampant Creative Group
              Mar 25 '14 at 10:54





              @EasyBB - if you're going to say never to use something, I't helpful to explain why. I have a situation in which I can't think of any other way to accomplish what I'm doing other than eval()

              – Rampant Creative Group
              Mar 25 '14 at 10:54




              2




              2





              Eval poses a risk for attacks on end users and we'll it's not technically evil rather misunderstood and misused in a lost of cases. I've seen php responses which hold literal vars in it then use eval to run it. Though this shouldn't be used in this case as there are better methods. This question at hand eval should not be used at all as there are better methods overall and I'm sure a lot of us know this.

              – EasyBB
              Mar 25 '14 at 13:26





              Eval poses a risk for attacks on end users and we'll it's not technically evil rather misunderstood and misused in a lost of cases. I've seen php responses which hold literal vars in it then use eval to run it. Though this shouldn't be used in this case as there are better methods. This question at hand eval should not be used at all as there are better methods overall and I'm sure a lot of us know this.

              – EasyBB
              Mar 25 '14 at 13:26




              2




              2





              Via javascriptweblog.wordpress.com/2010/04/19/how-evil-is-eval --- "Let’s consider the arguments most frequently leveled against using eval: 1) It requires a compile and is therefore slow 2) What if a malicious script found its way into the eval argument? 3) It looks ugly 4) It inherits the execution context and this binding of the scope in which its invoked"

              – mattLummus
              May 13 '15 at 15:07






              Via javascriptweblog.wordpress.com/2010/04/19/how-evil-is-eval --- "Let’s consider the arguments most frequently leveled against using eval: 1) It requires a compile and is therefore slow 2) What if a malicious script found its way into the eval argument? 3) It looks ugly 4) It inherits the execution context and this binding of the scope in which its invoked"

              – mattLummus
              May 13 '15 at 15:07





              1




              1





              Here is how to create dynamic variables using eval: stackoverflow.com/a/13291766/5528600

              – am2124429
              Mar 21 '16 at 12:54





              Here is how to create dynamic variables using eval: stackoverflow.com/a/13291766/5528600

              – am2124429
              Mar 21 '16 at 12:54











              69














              You can use the window object to get at it .



              window['myVar']


              window has a reference to all global variables and global functions you are using.






              share|improve this answer




















              • 24





                And needless to say, this one is safer than eval().

                – Cray
                Feb 25 '11 at 12:23















              69














              You can use the window object to get at it .



              window['myVar']


              window has a reference to all global variables and global functions you are using.






              share|improve this answer




















              • 24





                And needless to say, this one is safer than eval().

                – Cray
                Feb 25 '11 at 12:23













              69












              69








              69







              You can use the window object to get at it .



              window['myVar']


              window has a reference to all global variables and global functions you are using.






              share|improve this answer















              You can use the window object to get at it .



              window['myVar']


              window has a reference to all global variables and global functions you are using.







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Mar 30 '18 at 12:04









              Sebastian Palma

              16.5k42236




              16.5k42236










              answered Feb 25 '11 at 12:21









              JohnPJohnP

              42.8k891129




              42.8k891129







              • 24





                And needless to say, this one is safer than eval().

                – Cray
                Feb 25 '11 at 12:23












              • 24





                And needless to say, this one is safer than eval().

                – Cray
                Feb 25 '11 at 12:23







              24




              24





              And needless to say, this one is safer than eval().

              – Cray
              Feb 25 '11 at 12:23





              And needless to say, this one is safer than eval().

              – Cray
              Feb 25 '11 at 12:23











              34














              Just don't know what a bad answer gets so many votes. It's quite easy answer but you make it complex.



              // If you want to get article_count
              // var article_count = 1000;
              var type = 'article';
              this[type+'_count'] = 1000; // in a function we use "this";
              alert(article_count);





              share|improve this answer




















              • 9





                "in a function we use this" - If you want to access a global variable in this way, it is better to be explicit and use the window object, not this. this is ambiguous.

                – MrWhite
                Aug 23 '15 at 23:25















              34














              Just don't know what a bad answer gets so many votes. It's quite easy answer but you make it complex.



              // If you want to get article_count
              // var article_count = 1000;
              var type = 'article';
              this[type+'_count'] = 1000; // in a function we use "this";
              alert(article_count);





              share|improve this answer




















              • 9





                "in a function we use this" - If you want to access a global variable in this way, it is better to be explicit and use the window object, not this. this is ambiguous.

                – MrWhite
                Aug 23 '15 at 23:25













              34












              34








              34







              Just don't know what a bad answer gets so many votes. It's quite easy answer but you make it complex.



              // If you want to get article_count
              // var article_count = 1000;
              var type = 'article';
              this[type+'_count'] = 1000; // in a function we use "this";
              alert(article_count);





              share|improve this answer















              Just don't know what a bad answer gets so many votes. It's quite easy answer but you make it complex.



              // If you want to get article_count
              // var article_count = 1000;
              var type = 'article';
              this[type+'_count'] = 1000; // in a function we use "this";
              alert(article_count);






              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Jan 21 '15 at 9:39









              shkschneider

              11.3k114596




              11.3k114596










              answered Jan 21 '15 at 9:11









              Terry LinTerry Lin

              1,5741319




              1,5741319







              • 9





                "in a function we use this" - If you want to access a global variable in this way, it is better to be explicit and use the window object, not this. this is ambiguous.

                – MrWhite
                Aug 23 '15 at 23:25












              • 9





                "in a function we use this" - If you want to access a global variable in this way, it is better to be explicit and use the window object, not this. this is ambiguous.

                – MrWhite
                Aug 23 '15 at 23:25







              9




              9





              "in a function we use this" - If you want to access a global variable in this way, it is better to be explicit and use the window object, not this. this is ambiguous.

              – MrWhite
              Aug 23 '15 at 23:25





              "in a function we use this" - If you want to access a global variable in this way, it is better to be explicit and use the window object, not this. this is ambiguous.

              – MrWhite
              Aug 23 '15 at 23:25











              27














              a = 'varname';
              str = a+' = '+'123';
              eval(str)
              alert(varname);


              Try this...






              share|improve this answer



























                27














                a = 'varname';
                str = a+' = '+'123';
                eval(str)
                alert(varname);


                Try this...






                share|improve this answer

























                  27












                  27








                  27







                  a = 'varname';
                  str = a+' = '+'123';
                  eval(str)
                  alert(varname);


                  Try this...






                  share|improve this answer













                  a = 'varname';
                  str = a+' = '+'123';
                  eval(str)
                  alert(varname);


                  Try this...







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Feb 25 '11 at 12:23









                  amitchdamitchd

                  91958




                  91958





















                      23














                      This is an example :



                      for(var i=0; i<=3; i++) 
                      window['p'+i] = "hello " + i;


                      alert(p0); // hello 0
                      alert(p1); // hello 1
                      alert(p2); // hello 2
                      alert(p3); // hello 3


                      Another example :



                      var myVariable = 'coco';
                      window[myVariable] = 'riko';

                      alert(coco); // display : riko


                      So, the value "coco" of myVariable becomes a variable coco.



                      Because all the variables in the global scope are properties of the Window object.






                      share|improve this answer





























                        23














                        This is an example :



                        for(var i=0; i<=3; i++) 
                        window['p'+i] = "hello " + i;


                        alert(p0); // hello 0
                        alert(p1); // hello 1
                        alert(p2); // hello 2
                        alert(p3); // hello 3


                        Another example :



                        var myVariable = 'coco';
                        window[myVariable] = 'riko';

                        alert(coco); // display : riko


                        So, the value "coco" of myVariable becomes a variable coco.



                        Because all the variables in the global scope are properties of the Window object.






                        share|improve this answer



























                          23












                          23








                          23







                          This is an example :



                          for(var i=0; i<=3; i++) 
                          window['p'+i] = "hello " + i;


                          alert(p0); // hello 0
                          alert(p1); // hello 1
                          alert(p2); // hello 2
                          alert(p3); // hello 3


                          Another example :



                          var myVariable = 'coco';
                          window[myVariable] = 'riko';

                          alert(coco); // display : riko


                          So, the value "coco" of myVariable becomes a variable coco.



                          Because all the variables in the global scope are properties of the Window object.






                          share|improve this answer















                          This is an example :



                          for(var i=0; i<=3; i++) 
                          window['p'+i] = "hello " + i;


                          alert(p0); // hello 0
                          alert(p1); // hello 1
                          alert(p2); // hello 2
                          alert(p3); // hello 3


                          Another example :



                          var myVariable = 'coco';
                          window[myVariable] = 'riko';

                          alert(coco); // display : riko


                          So, the value "coco" of myVariable becomes a variable coco.



                          Because all the variables in the global scope are properties of the Window object.







                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited Nov 18 '16 at 12:05

























                          answered Jan 24 '15 at 20:55









                          AzodiumAzodium

                          1,07988




                          1,07988





















                              12














                              In Javascript you can use the fact that all properties are key value pairs. jAndy already mentioned this but I don't think his answer show how it can be exploited.



                              Usually you are not trying to create a variable to hold a variable name but are trying to generate variable names and then use them. PHP does it with $$var notation but Javascript doesn't need to because property keys are interchangeable with array keys.



                              var id = "abc";
                              var mine = ;
                              mine[id] = 123;
                              console.log(mine.abc);


                              gives 123. Usually you want to construct the variable which is why there is the indirection so you can also do it the other way around.



                              var mine = ;
                              mine.abc = 123;
                              console.log(mine["a"+"bc"]);





                              share|improve this answer


















                              • 1





                                var someJsonObj = ; in a loop.... for(var i=0; i<=3; i++) someJsonObj[i] = []; , but i can be anything. so dynamically generated variables, all sit inside someJsonObj for easy reference.

                                – rajeev
                                Apr 7 '17 at 6:31
















                              12














                              In Javascript you can use the fact that all properties are key value pairs. jAndy already mentioned this but I don't think his answer show how it can be exploited.



                              Usually you are not trying to create a variable to hold a variable name but are trying to generate variable names and then use them. PHP does it with $$var notation but Javascript doesn't need to because property keys are interchangeable with array keys.



                              var id = "abc";
                              var mine = ;
                              mine[id] = 123;
                              console.log(mine.abc);


                              gives 123. Usually you want to construct the variable which is why there is the indirection so you can also do it the other way around.



                              var mine = ;
                              mine.abc = 123;
                              console.log(mine["a"+"bc"]);





                              share|improve this answer


















                              • 1





                                var someJsonObj = ; in a loop.... for(var i=0; i<=3; i++) someJsonObj[i] = []; , but i can be anything. so dynamically generated variables, all sit inside someJsonObj for easy reference.

                                – rajeev
                                Apr 7 '17 at 6:31














                              12












                              12








                              12







                              In Javascript you can use the fact that all properties are key value pairs. jAndy already mentioned this but I don't think his answer show how it can be exploited.



                              Usually you are not trying to create a variable to hold a variable name but are trying to generate variable names and then use them. PHP does it with $$var notation but Javascript doesn't need to because property keys are interchangeable with array keys.



                              var id = "abc";
                              var mine = ;
                              mine[id] = 123;
                              console.log(mine.abc);


                              gives 123. Usually you want to construct the variable which is why there is the indirection so you can also do it the other way around.



                              var mine = ;
                              mine.abc = 123;
                              console.log(mine["a"+"bc"]);





                              share|improve this answer













                              In Javascript you can use the fact that all properties are key value pairs. jAndy already mentioned this but I don't think his answer show how it can be exploited.



                              Usually you are not trying to create a variable to hold a variable name but are trying to generate variable names and then use them. PHP does it with $$var notation but Javascript doesn't need to because property keys are interchangeable with array keys.



                              var id = "abc";
                              var mine = ;
                              mine[id] = 123;
                              console.log(mine.abc);


                              gives 123. Usually you want to construct the variable which is why there is the indirection so you can also do it the other way around.



                              var mine = ;
                              mine.abc = 123;
                              console.log(mine["a"+"bc"]);






                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered Nov 27 '14 at 2:42









                              David NewcombDavid Newcomb

                              9,04233449




                              9,04233449







                              • 1





                                var someJsonObj = ; in a loop.... for(var i=0; i<=3; i++) someJsonObj[i] = []; , but i can be anything. so dynamically generated variables, all sit inside someJsonObj for easy reference.

                                – rajeev
                                Apr 7 '17 at 6:31













                              • 1





                                var someJsonObj = ; in a loop.... for(var i=0; i<=3; i++) someJsonObj[i] = []; , but i can be anything. so dynamically generated variables, all sit inside someJsonObj for easy reference.

                                – rajeev
                                Apr 7 '17 at 6:31








                              1




                              1





                              var someJsonObj = ; in a loop.... for(var i=0; i<=3; i++) someJsonObj[i] = []; , but i can be anything. so dynamically generated variables, all sit inside someJsonObj for easy reference.

                              – rajeev
                              Apr 7 '17 at 6:31






                              var someJsonObj = ; in a loop.... for(var i=0; i<=3; i++) someJsonObj[i] = []; , but i can be anything. so dynamically generated variables, all sit inside someJsonObj for easy reference.

                              – rajeev
                              Apr 7 '17 at 6:31












                              4














                              If you don't want to use a global object like window or global (node), you can try something like this:



                              var obj = ;
                              obj['whatever'] = 'There's no need to store even more stuff in a global object.';

                              console.log(obj['whatever']);





                              share|improve this answer



























                                4














                                If you don't want to use a global object like window or global (node), you can try something like this:



                                var obj = ;
                                obj['whatever'] = 'There's no need to store even more stuff in a global object.';

                                console.log(obj['whatever']);





                                share|improve this answer

























                                  4












                                  4








                                  4







                                  If you don't want to use a global object like window or global (node), you can try something like this:



                                  var obj = ;
                                  obj['whatever'] = 'There's no need to store even more stuff in a global object.';

                                  console.log(obj['whatever']);





                                  share|improve this answer













                                  If you don't want to use a global object like window or global (node), you can try something like this:



                                  var obj = ;
                                  obj['whatever'] = 'There's no need to store even more stuff in a global object.';

                                  console.log(obj['whatever']);






                                  share|improve this answer












                                  share|improve this answer



                                  share|improve this answer










                                  answered Jan 30 '15 at 0:06









                                  Brent BarbataBrent Barbata

                                  2,63811920




                                  2,63811920





















                                      2














                                      I needed to draw multiple FormData on the fly and object way worked well



                                      var forms = 


                                      Then in my loops whereever i needed to create a form data i used



                                      forms["formdata"+counter]=new FormData();
                                      forms["formdata"+counter].append(var_name, var_value);





                                      share|improve this answer



























                                        2














                                        I needed to draw multiple FormData on the fly and object way worked well



                                        var forms = 


                                        Then in my loops whereever i needed to create a form data i used



                                        forms["formdata"+counter]=new FormData();
                                        forms["formdata"+counter].append(var_name, var_value);





                                        share|improve this answer

























                                          2












                                          2








                                          2







                                          I needed to draw multiple FormData on the fly and object way worked well



                                          var forms = 


                                          Then in my loops whereever i needed to create a form data i used



                                          forms["formdata"+counter]=new FormData();
                                          forms["formdata"+counter].append(var_name, var_value);





                                          share|improve this answer













                                          I needed to draw multiple FormData on the fly and object way worked well



                                          var forms = 


                                          Then in my loops whereever i needed to create a form data i used



                                          forms["formdata"+counter]=new FormData();
                                          forms["formdata"+counter].append(var_name, var_value);






                                          share|improve this answer












                                          share|improve this answer



                                          share|improve this answer










                                          answered Sep 17 '17 at 23:21









                                          TalhaTalha

                                          797812




                                          797812





















                                              2














                                              2019



                                              TL;DR




                                              • eval operator can run string expression in the context it called and return the value, also variables;


                                              • literal object theoretically can do that [varName], but it blocked by definition.

                                              So I come across this question and everyone here just play around without bringing a real solution. Thanks to @Axel Heider, who was approaching.



                                              The right solution is eval



                                              The almost most forgotten language operator. ( I think the most one is with )



                                              so reserve word operator eval can dynamically run expression in the context it called. and return the result of that expression. we can use that to dynamicly return a value of a variable in a function context.



                                              example:



                                              function exmaple1()
                                              var a = 1, b = 2, default = 3;
                                              var name = 'a';
                                              return eval(name)


                                              example1() // return 1


                                              function example2(option)
                                              var a = 1, b = 2, defaultValue = 3;

                                              switch(option)
                                              case 'a': name = 'a'; break;
                                              case 'b': name = 'b'; break;
                                              default: name = 'defaultValue';

                                              return eval (name);


                                              example2('a') // return 1
                                              example2('b') // return 2
                                              example2() // return 3


                                              Note that I always write explicitly the expression eval will run.
                                              To avoid unnecessary surprises in the code. eval is very strong

                                              But I'm sure you know that already



                                              BTW, if it was legal we could use literal object to capture the variable name and value, but we can’t combine computed property names and property value shorthand, sadly, is invalid



                                              functopn example( varName )
                                              var var1 = 'foo', var2 ='bar'

                                              var capture = [varName]



                                              example('var1') //trow 'Uncaught SyntaxError: Unexpected token }`





                                              share|improve this answer





























                                                2














                                                2019



                                                TL;DR




                                                • eval operator can run string expression in the context it called and return the value, also variables;


                                                • literal object theoretically can do that [varName], but it blocked by definition.

                                                So I come across this question and everyone here just play around without bringing a real solution. Thanks to @Axel Heider, who was approaching.



                                                The right solution is eval



                                                The almost most forgotten language operator. ( I think the most one is with )



                                                so reserve word operator eval can dynamically run expression in the context it called. and return the result of that expression. we can use that to dynamicly return a value of a variable in a function context.



                                                example:



                                                function exmaple1()
                                                var a = 1, b = 2, default = 3;
                                                var name = 'a';
                                                return eval(name)


                                                example1() // return 1


                                                function example2(option)
                                                var a = 1, b = 2, defaultValue = 3;

                                                switch(option)
                                                case 'a': name = 'a'; break;
                                                case 'b': name = 'b'; break;
                                                default: name = 'defaultValue';

                                                return eval (name);


                                                example2('a') // return 1
                                                example2('b') // return 2
                                                example2() // return 3


                                                Note that I always write explicitly the expression eval will run.
                                                To avoid unnecessary surprises in the code. eval is very strong

                                                But I'm sure you know that already



                                                BTW, if it was legal we could use literal object to capture the variable name and value, but we can’t combine computed property names and property value shorthand, sadly, is invalid



                                                functopn example( varName )
                                                var var1 = 'foo', var2 ='bar'

                                                var capture = [varName]



                                                example('var1') //trow 'Uncaught SyntaxError: Unexpected token }`





                                                share|improve this answer



























                                                  2












                                                  2








                                                  2







                                                  2019



                                                  TL;DR




                                                  • eval operator can run string expression in the context it called and return the value, also variables;


                                                  • literal object theoretically can do that [varName], but it blocked by definition.

                                                  So I come across this question and everyone here just play around without bringing a real solution. Thanks to @Axel Heider, who was approaching.



                                                  The right solution is eval



                                                  The almost most forgotten language operator. ( I think the most one is with )



                                                  so reserve word operator eval can dynamically run expression in the context it called. and return the result of that expression. we can use that to dynamicly return a value of a variable in a function context.



                                                  example:



                                                  function exmaple1()
                                                  var a = 1, b = 2, default = 3;
                                                  var name = 'a';
                                                  return eval(name)


                                                  example1() // return 1


                                                  function example2(option)
                                                  var a = 1, b = 2, defaultValue = 3;

                                                  switch(option)
                                                  case 'a': name = 'a'; break;
                                                  case 'b': name = 'b'; break;
                                                  default: name = 'defaultValue';

                                                  return eval (name);


                                                  example2('a') // return 1
                                                  example2('b') // return 2
                                                  example2() // return 3


                                                  Note that I always write explicitly the expression eval will run.
                                                  To avoid unnecessary surprises in the code. eval is very strong

                                                  But I'm sure you know that already



                                                  BTW, if it was legal we could use literal object to capture the variable name and value, but we can’t combine computed property names and property value shorthand, sadly, is invalid



                                                  functopn example( varName )
                                                  var var1 = 'foo', var2 ='bar'

                                                  var capture = [varName]



                                                  example('var1') //trow 'Uncaught SyntaxError: Unexpected token }`





                                                  share|improve this answer















                                                  2019



                                                  TL;DR




                                                  • eval operator can run string expression in the context it called and return the value, also variables;


                                                  • literal object theoretically can do that [varName], but it blocked by definition.

                                                  So I come across this question and everyone here just play around without bringing a real solution. Thanks to @Axel Heider, who was approaching.



                                                  The right solution is eval



                                                  The almost most forgotten language operator. ( I think the most one is with )



                                                  so reserve word operator eval can dynamically run expression in the context it called. and return the result of that expression. we can use that to dynamicly return a value of a variable in a function context.



                                                  example:



                                                  function exmaple1()
                                                  var a = 1, b = 2, default = 3;
                                                  var name = 'a';
                                                  return eval(name)


                                                  example1() // return 1


                                                  function example2(option)
                                                  var a = 1, b = 2, defaultValue = 3;

                                                  switch(option)
                                                  case 'a': name = 'a'; break;
                                                  case 'b': name = 'b'; break;
                                                  default: name = 'defaultValue';

                                                  return eval (name);


                                                  example2('a') // return 1
                                                  example2('b') // return 2
                                                  example2() // return 3


                                                  Note that I always write explicitly the expression eval will run.
                                                  To avoid unnecessary surprises in the code. eval is very strong

                                                  But I'm sure you know that already



                                                  BTW, if it was legal we could use literal object to capture the variable name and value, but we can’t combine computed property names and property value shorthand, sadly, is invalid



                                                  functopn example( varName )
                                                  var var1 = 'foo', var2 ='bar'

                                                  var capture = [varName]



                                                  example('var1') //trow 'Uncaught SyntaxError: Unexpected token }`






                                                  share|improve this answer














                                                  share|improve this answer



                                                  share|improve this answer








                                                  edited Jan 31 at 10:06

























                                                  answered Jan 4 at 19:08









                                                  pery mimonpery mimon

                                                  2,52522231




                                                  2,52522231





















                                                      1














                                                      what they mean is no, you can't.
                                                      there is no way to get it done.
                                                      so it was possible you could do something like this



                                                      function create(obj, const)
                                                      // where obj is an object and const is a variable name
                                                      function const ()

                                                      const.prototype.myProperty = property_value;
                                                      // .. more prototype

                                                      return new const();




                                                      having a create function just like the one implemented in ECMAScript 5.






                                                      share|improve this answer


















                                                      • 4





                                                        Beware: const is a keyword in ES6

                                                        – Tejas Manohar
                                                        Nov 17 '15 at 9:00






                                                      • 4





                                                        ...and prior to that was a future reserved word.

                                                        – T.J. Crowder
                                                        Dec 9 '15 at 16:23











                                                      • there is eval operator

                                                        – pery mimon
                                                        Jan 5 at 9:46















                                                      1














                                                      what they mean is no, you can't.
                                                      there is no way to get it done.
                                                      so it was possible you could do something like this



                                                      function create(obj, const)
                                                      // where obj is an object and const is a variable name
                                                      function const ()

                                                      const.prototype.myProperty = property_value;
                                                      // .. more prototype

                                                      return new const();




                                                      having a create function just like the one implemented in ECMAScript 5.






                                                      share|improve this answer


















                                                      • 4





                                                        Beware: const is a keyword in ES6

                                                        – Tejas Manohar
                                                        Nov 17 '15 at 9:00






                                                      • 4





                                                        ...and prior to that was a future reserved word.

                                                        – T.J. Crowder
                                                        Dec 9 '15 at 16:23











                                                      • there is eval operator

                                                        – pery mimon
                                                        Jan 5 at 9:46













                                                      1












                                                      1








                                                      1







                                                      what they mean is no, you can't.
                                                      there is no way to get it done.
                                                      so it was possible you could do something like this



                                                      function create(obj, const)
                                                      // where obj is an object and const is a variable name
                                                      function const ()

                                                      const.prototype.myProperty = property_value;
                                                      // .. more prototype

                                                      return new const();




                                                      having a create function just like the one implemented in ECMAScript 5.






                                                      share|improve this answer













                                                      what they mean is no, you can't.
                                                      there is no way to get it done.
                                                      so it was possible you could do something like this



                                                      function create(obj, const)
                                                      // where obj is an object and const is a variable name
                                                      function const ()

                                                      const.prototype.myProperty = property_value;
                                                      // .. more prototype

                                                      return new const();




                                                      having a create function just like the one implemented in ECMAScript 5.







                                                      share|improve this answer












                                                      share|improve this answer



                                                      share|improve this answer










                                                      answered Nov 24 '12 at 5:29









                                                      AlfgaarAlfgaar

                                                      14117




                                                      14117







                                                      • 4





                                                        Beware: const is a keyword in ES6

                                                        – Tejas Manohar
                                                        Nov 17 '15 at 9:00






                                                      • 4





                                                        ...and prior to that was a future reserved word.

                                                        – T.J. Crowder
                                                        Dec 9 '15 at 16:23











                                                      • there is eval operator

                                                        – pery mimon
                                                        Jan 5 at 9:46












                                                      • 4





                                                        Beware: const is a keyword in ES6

                                                        – Tejas Manohar
                                                        Nov 17 '15 at 9:00






                                                      • 4





                                                        ...and prior to that was a future reserved word.

                                                        – T.J. Crowder
                                                        Dec 9 '15 at 16:23











                                                      • there is eval operator

                                                        – pery mimon
                                                        Jan 5 at 9:46







                                                      4




                                                      4





                                                      Beware: const is a keyword in ES6

                                                      – Tejas Manohar
                                                      Nov 17 '15 at 9:00





                                                      Beware: const is a keyword in ES6

                                                      – Tejas Manohar
                                                      Nov 17 '15 at 9:00




                                                      4




                                                      4





                                                      ...and prior to that was a future reserved word.

                                                      – T.J. Crowder
                                                      Dec 9 '15 at 16:23





                                                      ...and prior to that was a future reserved word.

                                                      – T.J. Crowder
                                                      Dec 9 '15 at 16:23













                                                      there is eval operator

                                                      – pery mimon
                                                      Jan 5 at 9:46





                                                      there is eval operator

                                                      – pery mimon
                                                      Jan 5 at 9:46











                                                      1














                                                      eval() did not work in my tests. But adding new JavaScript code to the DOM tree is possible. So here is a function that adds a new variable:



                                                      function createVariable(varName,varContent)

                                                      var scriptStr = "var "+varName+"= ""+varContent+"""

                                                      var node_scriptCode = document.createTextNode( scriptStr )
                                                      var node_script = document.createElement("script");
                                                      node_script.type = "text/javascript"
                                                      node_script.appendChild(node_scriptCode);

                                                      var node_head = document.getElementsByTagName("head")[0]
                                                      node_head.appendChild(node_script);


                                                      createVariable("dynamicVar", "some content")
                                                      console.log(dynamicVar)





                                                      share|improve this answer




















                                                      • 2





                                                        small improvement, it is better to use var node_head = document.getElementsByTagName("head")[0] instead of ID, as no one gives an id="head" to <head> :-)

                                                        – ddlab
                                                        Nov 9 '14 at 17:41











                                                      • I do :) But thanks, now I can finally remove this `id="head" thing

                                                        – Axel Heider
                                                        May 4 '15 at 11:33







                                                      • 1





                                                        This just seems to be an overly complex way of creating a global variable?! (...and how does this answer the question?)

                                                        – MrWhite
                                                        Aug 23 '15 at 23:39











                                                      • genius :) eval is the solution. Even if your code does not work

                                                        – pery mimon
                                                        Jan 4 at 18:27















                                                      1














                                                      eval() did not work in my tests. But adding new JavaScript code to the DOM tree is possible. So here is a function that adds a new variable:



                                                      function createVariable(varName,varContent)

                                                      var scriptStr = "var "+varName+"= ""+varContent+"""

                                                      var node_scriptCode = document.createTextNode( scriptStr )
                                                      var node_script = document.createElement("script");
                                                      node_script.type = "text/javascript"
                                                      node_script.appendChild(node_scriptCode);

                                                      var node_head = document.getElementsByTagName("head")[0]
                                                      node_head.appendChild(node_script);


                                                      createVariable("dynamicVar", "some content")
                                                      console.log(dynamicVar)





                                                      share|improve this answer




















                                                      • 2





                                                        small improvement, it is better to use var node_head = document.getElementsByTagName("head")[0] instead of ID, as no one gives an id="head" to <head> :-)

                                                        – ddlab
                                                        Nov 9 '14 at 17:41











                                                      • I do :) But thanks, now I can finally remove this `id="head" thing

                                                        – Axel Heider
                                                        May 4 '15 at 11:33







                                                      • 1





                                                        This just seems to be an overly complex way of creating a global variable?! (...and how does this answer the question?)

                                                        – MrWhite
                                                        Aug 23 '15 at 23:39











                                                      • genius :) eval is the solution. Even if your code does not work

                                                        – pery mimon
                                                        Jan 4 at 18:27













                                                      1












                                                      1








                                                      1







                                                      eval() did not work in my tests. But adding new JavaScript code to the DOM tree is possible. So here is a function that adds a new variable:



                                                      function createVariable(varName,varContent)

                                                      var scriptStr = "var "+varName+"= ""+varContent+"""

                                                      var node_scriptCode = document.createTextNode( scriptStr )
                                                      var node_script = document.createElement("script");
                                                      node_script.type = "text/javascript"
                                                      node_script.appendChild(node_scriptCode);

                                                      var node_head = document.getElementsByTagName("head")[0]
                                                      node_head.appendChild(node_script);


                                                      createVariable("dynamicVar", "some content")
                                                      console.log(dynamicVar)





                                                      share|improve this answer















                                                      eval() did not work in my tests. But adding new JavaScript code to the DOM tree is possible. So here is a function that adds a new variable:



                                                      function createVariable(varName,varContent)

                                                      var scriptStr = "var "+varName+"= ""+varContent+"""

                                                      var node_scriptCode = document.createTextNode( scriptStr )
                                                      var node_script = document.createElement("script");
                                                      node_script.type = "text/javascript"
                                                      node_script.appendChild(node_scriptCode);

                                                      var node_head = document.getElementsByTagName("head")[0]
                                                      node_head.appendChild(node_script);


                                                      createVariable("dynamicVar", "some content")
                                                      console.log(dynamicVar)






                                                      share|improve this answer














                                                      share|improve this answer



                                                      share|improve this answer








                                                      edited May 4 '15 at 11:37

























                                                      answered Oct 5 '14 at 22:50









                                                      Axel HeiderAxel Heider

                                                      187110




                                                      187110







                                                      • 2





                                                        small improvement, it is better to use var node_head = document.getElementsByTagName("head")[0] instead of ID, as no one gives an id="head" to <head> :-)

                                                        – ddlab
                                                        Nov 9 '14 at 17:41











                                                      • I do :) But thanks, now I can finally remove this `id="head" thing

                                                        – Axel Heider
                                                        May 4 '15 at 11:33







                                                      • 1





                                                        This just seems to be an overly complex way of creating a global variable?! (...and how does this answer the question?)

                                                        – MrWhite
                                                        Aug 23 '15 at 23:39











                                                      • genius :) eval is the solution. Even if your code does not work

                                                        – pery mimon
                                                        Jan 4 at 18:27












                                                      • 2





                                                        small improvement, it is better to use var node_head = document.getElementsByTagName("head")[0] instead of ID, as no one gives an id="head" to <head> :-)

                                                        – ddlab
                                                        Nov 9 '14 at 17:41











                                                      • I do :) But thanks, now I can finally remove this `id="head" thing

                                                        – Axel Heider
                                                        May 4 '15 at 11:33







                                                      • 1





                                                        This just seems to be an overly complex way of creating a global variable?! (...and how does this answer the question?)

                                                        – MrWhite
                                                        Aug 23 '15 at 23:39











                                                      • genius :) eval is the solution. Even if your code does not work

                                                        – pery mimon
                                                        Jan 4 at 18:27







                                                      2




                                                      2





                                                      small improvement, it is better to use var node_head = document.getElementsByTagName("head")[0] instead of ID, as no one gives an id="head" to <head> :-)

                                                      – ddlab
                                                      Nov 9 '14 at 17:41





                                                      small improvement, it is better to use var node_head = document.getElementsByTagName("head")[0] instead of ID, as no one gives an id="head" to <head> :-)

                                                      – ddlab
                                                      Nov 9 '14 at 17:41













                                                      I do :) But thanks, now I can finally remove this `id="head" thing

                                                      – Axel Heider
                                                      May 4 '15 at 11:33






                                                      I do :) But thanks, now I can finally remove this `id="head" thing

                                                      – Axel Heider
                                                      May 4 '15 at 11:33





                                                      1




                                                      1





                                                      This just seems to be an overly complex way of creating a global variable?! (...and how does this answer the question?)

                                                      – MrWhite
                                                      Aug 23 '15 at 23:39





                                                      This just seems to be an overly complex way of creating a global variable?! (...and how does this answer the question?)

                                                      – MrWhite
                                                      Aug 23 '15 at 23:39













                                                      genius :) eval is the solution. Even if your code does not work

                                                      – pery mimon
                                                      Jan 4 at 18:27





                                                      genius :) eval is the solution. Even if your code does not work

                                                      – pery mimon
                                                      Jan 4 at 18:27











                                                      0














                                                      use Object is great too.



                                                      var a=123
                                                      var b=234
                                                      var temp = "a":a,"b":b
                                                      console.log(temp["a"],temp["b"]);





                                                      share|improve this answer



























                                                        0














                                                        use Object is great too.



                                                        var a=123
                                                        var b=234
                                                        var temp = "a":a,"b":b
                                                        console.log(temp["a"],temp["b"]);





                                                        share|improve this answer

























                                                          0












                                                          0








                                                          0







                                                          use Object is great too.



                                                          var a=123
                                                          var b=234
                                                          var temp = "a":a,"b":b
                                                          console.log(temp["a"],temp["b"]);





                                                          share|improve this answer













                                                          use Object is great too.



                                                          var a=123
                                                          var b=234
                                                          var temp = "a":a,"b":b
                                                          console.log(temp["a"],temp["b"]);






                                                          share|improve this answer












                                                          share|improve this answer



                                                          share|improve this answer










                                                          answered Mar 20 at 7:58









                                                          Steve JiangSteve Jiang

                                                          347313




                                                          347313





















                                                              0














                                                              Although this have an accepted answer I would like to add an observation:



                                                              In ES6 using let doesn't work:






                                                              /*this is NOT working*/
                                                              let t = "skyBlue",
                                                              m = "gold",
                                                              b = "tomato";

                                                              let color = window["b"];
                                                              console.log(color);





                                                              However using var works






                                                              /*this IS working*/
                                                              var t = "skyBlue",
                                                              m = "gold",
                                                              b = "tomato";

                                                              let color = window["b"];
                                                              console.log(color);





                                                              I hope this may be useful to some.






                                                              share|improve this answer


















                                                              • 1





                                                                same applies to const

                                                                – user4244405
                                                                Apr 19 at 8:26















                                                              0














                                                              Although this have an accepted answer I would like to add an observation:



                                                              In ES6 using let doesn't work:






                                                              /*this is NOT working*/
                                                              let t = "skyBlue",
                                                              m = "gold",
                                                              b = "tomato";

                                                              let color = window["b"];
                                                              console.log(color);





                                                              However using var works






                                                              /*this IS working*/
                                                              var t = "skyBlue",
                                                              m = "gold",
                                                              b = "tomato";

                                                              let color = window["b"];
                                                              console.log(color);





                                                              I hope this may be useful to some.






                                                              share|improve this answer


















                                                              • 1





                                                                same applies to const

                                                                – user4244405
                                                                Apr 19 at 8:26













                                                              0












                                                              0








                                                              0







                                                              Although this have an accepted answer I would like to add an observation:



                                                              In ES6 using let doesn't work:






                                                              /*this is NOT working*/
                                                              let t = "skyBlue",
                                                              m = "gold",
                                                              b = "tomato";

                                                              let color = window["b"];
                                                              console.log(color);





                                                              However using var works






                                                              /*this IS working*/
                                                              var t = "skyBlue",
                                                              m = "gold",
                                                              b = "tomato";

                                                              let color = window["b"];
                                                              console.log(color);





                                                              I hope this may be useful to some.






                                                              share|improve this answer













                                                              Although this have an accepted answer I would like to add an observation:



                                                              In ES6 using let doesn't work:






                                                              /*this is NOT working*/
                                                              let t = "skyBlue",
                                                              m = "gold",
                                                              b = "tomato";

                                                              let color = window["b"];
                                                              console.log(color);





                                                              However using var works






                                                              /*this IS working*/
                                                              var t = "skyBlue",
                                                              m = "gold",
                                                              b = "tomato";

                                                              let color = window["b"];
                                                              console.log(color);





                                                              I hope this may be useful to some.






                                                              /*this is NOT working*/
                                                              let t = "skyBlue",
                                                              m = "gold",
                                                              b = "tomato";

                                                              let color = window["b"];
                                                              console.log(color);





                                                              /*this is NOT working*/
                                                              let t = "skyBlue",
                                                              m = "gold",
                                                              b = "tomato";

                                                              let color = window["b"];
                                                              console.log(color);





                                                              /*this IS working*/
                                                              var t = "skyBlue",
                                                              m = "gold",
                                                              b = "tomato";

                                                              let color = window["b"];
                                                              console.log(color);





                                                              /*this IS working*/
                                                              var t = "skyBlue",
                                                              m = "gold",
                                                              b = "tomato";

                                                              let color = window["b"];
                                                              console.log(color);






                                                              share|improve this answer












                                                              share|improve this answer



                                                              share|improve this answer










                                                              answered Mar 23 at 9:36









                                                              enxanetaenxaneta

                                                              11.4k2821




                                                              11.4k2821







                                                              • 1





                                                                same applies to const

                                                                – user4244405
                                                                Apr 19 at 8:26












                                                              • 1





                                                                same applies to const

                                                                – user4244405
                                                                Apr 19 at 8:26







                                                              1




                                                              1





                                                              same applies to const

                                                              – user4244405
                                                              Apr 19 at 8:26





                                                              same applies to const

                                                              – user4244405
                                                              Apr 19 at 8:26





                                                              protected by Community Apr 11 '18 at 16:47



                                                              Thank you for your interest in this question.
                                                              Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



                                                              Would you like to answer one of these unanswered questions instead?



                                                              Popular posts from this blog

                                                              SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                                                              용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

                                                              155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해