Get global variable dynamically by name string in 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>

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

Tags:

Javascript