Get global variable dynamically by name string in JavaScript












65















<script>
//in one script
var someVarName_10 = 20;
</script>


I want to get access to this variable from another script by name of variable. With window object its simple, is it possible with local variable?



I mean access this var by code like this:



<script>
alert(all_vars['someVar' + 'Name' + num]);
</script>









share|improve this question




















  • 1





    Your sample shows a global variable. You want to know if you can access it from a local scope?

    – Crescent Fresh
    Dec 17 '09 at 10:46











  • It really depends on what you mean by 'local scope'.. Javascript functions are scoped only to functions, not blocks or even files

    – K Prime
    Dec 17 '09 at 10:50











  • possible duplicate of Is there a way to access a javascript variable using a string that contains the name of the variable?

    – Gilles
    May 29 '11 at 20:56
















65















<script>
//in one script
var someVarName_10 = 20;
</script>


I want to get access to this variable from another script by name of variable. With window object its simple, is it possible with local variable?



I mean access this var by code like this:



<script>
alert(all_vars['someVar' + 'Name' + num]);
</script>









share|improve this question




















  • 1





    Your sample shows a global variable. You want to know if you can access it from a local scope?

    – Crescent Fresh
    Dec 17 '09 at 10:46











  • It really depends on what you mean by 'local scope'.. Javascript functions are scoped only to functions, not blocks or even files

    – K Prime
    Dec 17 '09 at 10:50











  • possible duplicate of Is there a way to access a javascript variable using a string that contains the name of the variable?

    – Gilles
    May 29 '11 at 20:56














65












65








65


12






<script>
//in one script
var someVarName_10 = 20;
</script>


I want to get access to this variable from another script by name of variable. With window object its simple, is it possible with local variable?



I mean access this var by code like this:



<script>
alert(all_vars['someVar' + 'Name' + num]);
</script>









share|improve this question
















<script>
//in one script
var someVarName_10 = 20;
</script>


I want to get access to this variable from another script by name of variable. With window object its simple, is it possible with local variable?



I mean access this var by code like this:



<script>
alert(all_vars['someVar' + 'Name' + num]);
</script>






javascript






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 12 '16 at 19:18









Michał Perłakowski

42.2k1699115




42.2k1699115










asked Dec 17 '09 at 10:43









appqui-platformappqui-platform

1,94763458




1,94763458








  • 1





    Your sample shows a global variable. You want to know if you can access it from a local scope?

    – Crescent Fresh
    Dec 17 '09 at 10:46











  • It really depends on what you mean by 'local scope'.. Javascript functions are scoped only to functions, not blocks or even files

    – K Prime
    Dec 17 '09 at 10:50











  • possible duplicate of Is there a way to access a javascript variable using a string that contains the name of the variable?

    – Gilles
    May 29 '11 at 20:56














  • 1





    Your sample shows a global variable. You want to know if you can access it from a local scope?

    – Crescent Fresh
    Dec 17 '09 at 10:46











  • It really depends on what you mean by 'local scope'.. Javascript functions are scoped only to functions, not blocks or even files

    – K Prime
    Dec 17 '09 at 10:50











  • possible duplicate of Is there a way to access a javascript variable using a string that contains the name of the variable?

    – Gilles
    May 29 '11 at 20:56








1




1





Your sample shows a global variable. You want to know if you can access it from a local scope?

– Crescent Fresh
Dec 17 '09 at 10:46





Your sample shows a global variable. You want to know if you can access it from a local scope?

– Crescent Fresh
Dec 17 '09 at 10:46













It really depends on what you mean by 'local scope'.. Javascript functions are scoped only to functions, not blocks or even files

– K Prime
Dec 17 '09 at 10:50





It really depends on what you mean by 'local scope'.. Javascript functions are scoped only to functions, not blocks or even files

– K Prime
Dec 17 '09 at 10:50













possible duplicate of Is there a way to access a javascript variable using a string that contains the name of the variable?

– Gilles
May 29 '11 at 20:56





possible duplicate of Is there a way to access a javascript variable using a string that contains the name of the variable?

– Gilles
May 29 '11 at 20:56












5 Answers
5






active

oldest

votes


















93














Do you want to do something like this?



<script>
//in one script
var someVarName_10 = 20;

alert(window["someVarName_10"]); //alert 20

</script>


Update: because OP edited the question.



<script>
num=10;
alert(window['someVar' + 'Name_' + num]); //alert 20
</script>





share|improve this answer
























  • sorry, I was wrong, i thought that vars are not in window, thanks

    – appqui-platform
    Dec 17 '09 at 10:59











  • you're welcome.

    – YOU
    Dec 17 '09 at 11:00






  • 5





    I don't care what OP actually wanted. I care about what is in question title and therefore becomes google result in my searches.

    – Tomáš Zato
    Oct 22 '15 at 8:15






  • 1





    @DeepakChaudhary, may be you want something like lodash's _.get? - lodash.com/docs#get

    – YOU
    Aug 2 '16 at 15:45








  • 1





    That would be window["a"].name;

    – Repo
    Mar 28 '17 at 8:13



















33














I've noticed that everyone is advising global var creation this will lead to variables leak to global namespace.
When you dynamically creating classnames or just variables it's easy to keep em local:



this['className'] = 123;


or



this['varName'] = 123;


Name-spacing would look like this:



vars = {};
vars['varName'] = 123;
vars.varName // 123





share|improve this answer





















  • 1





    var this['className'] = 123; looks like a syntax error to me.

    – Felix Kling
    Jan 19 '13 at 1:33











  • you right i don't know why I added var

    – Andrew Shatnyy
    Apr 7 '13 at 19:54






  • 1





    This is better than accepted answer. More descriptive about how this feature works in class scopes.

    – Sellorio
    Jun 22 '15 at 1:54



















10














<script>
var someVarName_10 = 20;
var num = 10;
alert(eval('someVar' + 'Name_' + num)); //alert 20
</script>





share|improve this answer
























  • eval worked better for me! but use it with caution

    – papaiatis
    Nov 9 '16 at 13:14



















1














well, for debugging purpose only, you could do something like this. I use it during the development of classes, where some variables must remain private (var). this work even in local variable (and global of curse)



function MYCLASS(){
var a=1, b=2, c=3;
this.public = "variable";
this.debug = function(sVar){
return eval(sVar);
}
}

var myThing = new MYCLASS();
myThing.debug('a') //return 1
myThing.debug('b') //return 2
myThing.debug('c') //return 3





share|improve this answer































    -5














    If this is what you said:



    <script type="text/javascript">
    var hello = 'test';
    </script>
    <script type="text/javascript">
    alert (hello);
    </script>


    It works because script are finally available to the document and you can access their vars.






    share|improve this answer























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f1920867%2fget-global-variable-dynamically-by-name-string-in-javascript%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      5 Answers
      5






      active

      oldest

      votes








      5 Answers
      5






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      93














      Do you want to do something like this?



      <script>
      //in one script
      var someVarName_10 = 20;

      alert(window["someVarName_10"]); //alert 20

      </script>


      Update: because OP edited the question.



      <script>
      num=10;
      alert(window['someVar' + 'Name_' + num]); //alert 20
      </script>





      share|improve this answer
























      • sorry, I was wrong, i thought that vars are not in window, thanks

        – appqui-platform
        Dec 17 '09 at 10:59











      • you're welcome.

        – YOU
        Dec 17 '09 at 11:00






      • 5





        I don't care what OP actually wanted. I care about what is in question title and therefore becomes google result in my searches.

        – Tomáš Zato
        Oct 22 '15 at 8:15






      • 1





        @DeepakChaudhary, may be you want something like lodash's _.get? - lodash.com/docs#get

        – YOU
        Aug 2 '16 at 15:45








      • 1





        That would be window["a"].name;

        – Repo
        Mar 28 '17 at 8:13
















      93














      Do you want to do something like this?



      <script>
      //in one script
      var someVarName_10 = 20;

      alert(window["someVarName_10"]); //alert 20

      </script>


      Update: because OP edited the question.



      <script>
      num=10;
      alert(window['someVar' + 'Name_' + num]); //alert 20
      </script>





      share|improve this answer
























      • sorry, I was wrong, i thought that vars are not in window, thanks

        – appqui-platform
        Dec 17 '09 at 10:59











      • you're welcome.

        – YOU
        Dec 17 '09 at 11:00






      • 5





        I don't care what OP actually wanted. I care about what is in question title and therefore becomes google result in my searches.

        – Tomáš Zato
        Oct 22 '15 at 8:15






      • 1





        @DeepakChaudhary, may be you want something like lodash's _.get? - lodash.com/docs#get

        – YOU
        Aug 2 '16 at 15:45








      • 1





        That would be window["a"].name;

        – Repo
        Mar 28 '17 at 8:13














      93












      93








      93







      Do you want to do something like this?



      <script>
      //in one script
      var someVarName_10 = 20;

      alert(window["someVarName_10"]); //alert 20

      </script>


      Update: because OP edited the question.



      <script>
      num=10;
      alert(window['someVar' + 'Name_' + num]); //alert 20
      </script>





      share|improve this answer













      Do you want to do something like this?



      <script>
      //in one script
      var someVarName_10 = 20;

      alert(window["someVarName_10"]); //alert 20

      </script>


      Update: because OP edited the question.



      <script>
      num=10;
      alert(window['someVar' + 'Name_' + num]); //alert 20
      </script>






      share|improve this answer












      share|improve this answer



      share|improve this answer










      answered Dec 17 '09 at 10:53









      YOUYOU

      84.7k20151199




      84.7k20151199













      • sorry, I was wrong, i thought that vars are not in window, thanks

        – appqui-platform
        Dec 17 '09 at 10:59











      • you're welcome.

        – YOU
        Dec 17 '09 at 11:00






      • 5





        I don't care what OP actually wanted. I care about what is in question title and therefore becomes google result in my searches.

        – Tomáš Zato
        Oct 22 '15 at 8:15






      • 1





        @DeepakChaudhary, may be you want something like lodash's _.get? - lodash.com/docs#get

        – YOU
        Aug 2 '16 at 15:45








      • 1





        That would be window["a"].name;

        – Repo
        Mar 28 '17 at 8:13



















      • sorry, I was wrong, i thought that vars are not in window, thanks

        – appqui-platform
        Dec 17 '09 at 10:59











      • you're welcome.

        – YOU
        Dec 17 '09 at 11:00






      • 5





        I don't care what OP actually wanted. I care about what is in question title and therefore becomes google result in my searches.

        – Tomáš Zato
        Oct 22 '15 at 8:15






      • 1





        @DeepakChaudhary, may be you want something like lodash's _.get? - lodash.com/docs#get

        – YOU
        Aug 2 '16 at 15:45








      • 1





        That would be window["a"].name;

        – Repo
        Mar 28 '17 at 8:13

















      sorry, I was wrong, i thought that vars are not in window, thanks

      – appqui-platform
      Dec 17 '09 at 10:59





      sorry, I was wrong, i thought that vars are not in window, thanks

      – appqui-platform
      Dec 17 '09 at 10:59













      you're welcome.

      – YOU
      Dec 17 '09 at 11:00





      you're welcome.

      – YOU
      Dec 17 '09 at 11:00




      5




      5





      I don't care what OP actually wanted. I care about what is in question title and therefore becomes google result in my searches.

      – Tomáš Zato
      Oct 22 '15 at 8:15





      I don't care what OP actually wanted. I care about what is in question title and therefore becomes google result in my searches.

      – Tomáš Zato
      Oct 22 '15 at 8:15




      1




      1





      @DeepakChaudhary, may be you want something like lodash's _.get? - lodash.com/docs#get

      – YOU
      Aug 2 '16 at 15:45







      @DeepakChaudhary, may be you want something like lodash's _.get? - lodash.com/docs#get

      – YOU
      Aug 2 '16 at 15:45






      1




      1





      That would be window["a"].name;

      – Repo
      Mar 28 '17 at 8:13





      That would be window["a"].name;

      – Repo
      Mar 28 '17 at 8:13













      33














      I've noticed that everyone is advising global var creation this will lead to variables leak to global namespace.
      When you dynamically creating classnames or just variables it's easy to keep em local:



      this['className'] = 123;


      or



      this['varName'] = 123;


      Name-spacing would look like this:



      vars = {};
      vars['varName'] = 123;
      vars.varName // 123





      share|improve this answer





















      • 1





        var this['className'] = 123; looks like a syntax error to me.

        – Felix Kling
        Jan 19 '13 at 1:33











      • you right i don't know why I added var

        – Andrew Shatnyy
        Apr 7 '13 at 19:54






      • 1





        This is better than accepted answer. More descriptive about how this feature works in class scopes.

        – Sellorio
        Jun 22 '15 at 1:54
















      33














      I've noticed that everyone is advising global var creation this will lead to variables leak to global namespace.
      When you dynamically creating classnames or just variables it's easy to keep em local:



      this['className'] = 123;


      or



      this['varName'] = 123;


      Name-spacing would look like this:



      vars = {};
      vars['varName'] = 123;
      vars.varName // 123





      share|improve this answer





















      • 1





        var this['className'] = 123; looks like a syntax error to me.

        – Felix Kling
        Jan 19 '13 at 1:33











      • you right i don't know why I added var

        – Andrew Shatnyy
        Apr 7 '13 at 19:54






      • 1





        This is better than accepted answer. More descriptive about how this feature works in class scopes.

        – Sellorio
        Jun 22 '15 at 1:54














      33












      33








      33







      I've noticed that everyone is advising global var creation this will lead to variables leak to global namespace.
      When you dynamically creating classnames or just variables it's easy to keep em local:



      this['className'] = 123;


      or



      this['varName'] = 123;


      Name-spacing would look like this:



      vars = {};
      vars['varName'] = 123;
      vars.varName // 123





      share|improve this answer















      I've noticed that everyone is advising global var creation this will lead to variables leak to global namespace.
      When you dynamically creating classnames or just variables it's easy to keep em local:



      this['className'] = 123;


      or



      this['varName'] = 123;


      Name-spacing would look like this:



      vars = {};
      vars['varName'] = 123;
      vars.varName // 123






      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Jul 2 '13 at 17:09









      yckart

      20.7k593107




      20.7k593107










      answered Sep 8 '12 at 21:08









      Andrew ShatnyyAndrew Shatnyy

      1,1111019




      1,1111019








      • 1





        var this['className'] = 123; looks like a syntax error to me.

        – Felix Kling
        Jan 19 '13 at 1:33











      • you right i don't know why I added var

        – Andrew Shatnyy
        Apr 7 '13 at 19:54






      • 1





        This is better than accepted answer. More descriptive about how this feature works in class scopes.

        – Sellorio
        Jun 22 '15 at 1:54














      • 1





        var this['className'] = 123; looks like a syntax error to me.

        – Felix Kling
        Jan 19 '13 at 1:33











      • you right i don't know why I added var

        – Andrew Shatnyy
        Apr 7 '13 at 19:54






      • 1





        This is better than accepted answer. More descriptive about how this feature works in class scopes.

        – Sellorio
        Jun 22 '15 at 1:54








      1




      1





      var this['className'] = 123; looks like a syntax error to me.

      – Felix Kling
      Jan 19 '13 at 1:33





      var this['className'] = 123; looks like a syntax error to me.

      – Felix Kling
      Jan 19 '13 at 1:33













      you right i don't know why I added var

      – Andrew Shatnyy
      Apr 7 '13 at 19:54





      you right i don't know why I added var

      – Andrew Shatnyy
      Apr 7 '13 at 19:54




      1




      1





      This is better than accepted answer. More descriptive about how this feature works in class scopes.

      – Sellorio
      Jun 22 '15 at 1:54





      This is better than accepted answer. More descriptive about how this feature works in class scopes.

      – Sellorio
      Jun 22 '15 at 1:54











      10














      <script>
      var someVarName_10 = 20;
      var num = 10;
      alert(eval('someVar' + 'Name_' + num)); //alert 20
      </script>





      share|improve this answer
























      • eval worked better for me! but use it with caution

        – papaiatis
        Nov 9 '16 at 13:14
















      10














      <script>
      var someVarName_10 = 20;
      var num = 10;
      alert(eval('someVar' + 'Name_' + num)); //alert 20
      </script>





      share|improve this answer
























      • eval worked better for me! but use it with caution

        – papaiatis
        Nov 9 '16 at 13:14














      10












      10








      10







      <script>
      var someVarName_10 = 20;
      var num = 10;
      alert(eval('someVar' + 'Name_' + num)); //alert 20
      </script>





      share|improve this answer













      <script>
      var someVarName_10 = 20;
      var num = 10;
      alert(eval('someVar' + 'Name_' + num)); //alert 20
      </script>






      share|improve this answer












      share|improve this answer



      share|improve this answer










      answered Jan 16 '15 at 16:39









      Matteo BaroniMatteo Baroni

      10913




      10913













      • eval worked better for me! but use it with caution

        – papaiatis
        Nov 9 '16 at 13:14



















      • eval worked better for me! but use it with caution

        – papaiatis
        Nov 9 '16 at 13:14

















      eval worked better for me! but use it with caution

      – papaiatis
      Nov 9 '16 at 13:14





      eval worked better for me! but use it with caution

      – papaiatis
      Nov 9 '16 at 13:14











      1














      well, for debugging purpose only, you could do something like this. I use it during the development of classes, where some variables must remain private (var). this work even in local variable (and global of curse)



      function MYCLASS(){
      var a=1, b=2, c=3;
      this.public = "variable";
      this.debug = function(sVar){
      return eval(sVar);
      }
      }

      var myThing = new MYCLASS();
      myThing.debug('a') //return 1
      myThing.debug('b') //return 2
      myThing.debug('c') //return 3





      share|improve this answer




























        1














        well, for debugging purpose only, you could do something like this. I use it during the development of classes, where some variables must remain private (var). this work even in local variable (and global of curse)



        function MYCLASS(){
        var a=1, b=2, c=3;
        this.public = "variable";
        this.debug = function(sVar){
        return eval(sVar);
        }
        }

        var myThing = new MYCLASS();
        myThing.debug('a') //return 1
        myThing.debug('b') //return 2
        myThing.debug('c') //return 3





        share|improve this answer


























          1












          1








          1







          well, for debugging purpose only, you could do something like this. I use it during the development of classes, where some variables must remain private (var). this work even in local variable (and global of curse)



          function MYCLASS(){
          var a=1, b=2, c=3;
          this.public = "variable";
          this.debug = function(sVar){
          return eval(sVar);
          }
          }

          var myThing = new MYCLASS();
          myThing.debug('a') //return 1
          myThing.debug('b') //return 2
          myThing.debug('c') //return 3





          share|improve this answer













          well, for debugging purpose only, you could do something like this. I use it during the development of classes, where some variables must remain private (var). this work even in local variable (and global of curse)



          function MYCLASS(){
          var a=1, b=2, c=3;
          this.public = "variable";
          this.debug = function(sVar){
          return eval(sVar);
          }
          }

          var myThing = new MYCLASS();
          myThing.debug('a') //return 1
          myThing.debug('b') //return 2
          myThing.debug('c') //return 3






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Sep 16 '15 at 15:38









          Nereo CostacurtaNereo Costacurta

          1,55831423




          1,55831423























              -5














              If this is what you said:



              <script type="text/javascript">
              var hello = 'test';
              </script>
              <script type="text/javascript">
              alert (hello);
              </script>


              It works because script are finally available to the document and you can access their vars.






              share|improve this answer




























                -5














                If this is what you said:



                <script type="text/javascript">
                var hello = 'test';
                </script>
                <script type="text/javascript">
                alert (hello);
                </script>


                It works because script are finally available to the document and you can access their vars.






                share|improve this answer


























                  -5












                  -5








                  -5







                  If this is what you said:



                  <script type="text/javascript">
                  var hello = 'test';
                  </script>
                  <script type="text/javascript">
                  alert (hello);
                  </script>


                  It works because script are finally available to the document and you can access their vars.






                  share|improve this answer













                  If this is what you said:



                  <script type="text/javascript">
                  var hello = 'test';
                  </script>
                  <script type="text/javascript">
                  alert (hello);
                  </script>


                  It works because script are finally available to the document and you can access their vars.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Dec 17 '09 at 10:46









                  SarfrazSarfraz

                  299k64471547




                  299k64471547






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f1920867%2fget-global-variable-dynamically-by-name-string-in-javascript%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Guess what letter conforming each word

                      Port of Spain

                      Run scheduled task as local user group (not BUILTIN)