Get global variable dynamically by name string in JavaScript

Javascript

Javascript Problem Overview


<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 Solutions


Solution 1 - Javascript

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>

Solution 2 - Javascript

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

Solution 3 - Javascript

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

Solution 4 - Javascript

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

Solution 5 - Javascript

This is not my own answer, its Arthur Araújo's answer, but I think its relevent here.


Eval alternative:

exp = '1 + 1'
x = Function('return ' + exp)()
console.log(x)

Solution 6 - Javascript

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionIgor GolodnitskyView Question on Stackoverflow
Solution 1 - JavascriptYOUView Answer on Stackoverflow
Solution 2 - JavascriptAndrew ShatnyyView Answer on Stackoverflow
Solution 3 - JavascriptMatteo BaroniView Answer on Stackoverflow
Solution 4 - JavascriptNereo CostacurtaView Answer on Stackoverflow
Solution 5 - JavascriptElronView Answer on Stackoverflow
Solution 6 - JavascriptSarfrazView Answer on Stackoverflow