Generate variable names dynamically in Javascript

Suppose you want to use the value of one variable as part of the name of another variable, but you don’t know the exact name of the first variable, because it will be selected by user input.

For example, suppose you want a variable “itemArray” to be assigned any of several possible lists of items, depending on what your users select.

If the lists are named itemArray1, itemArray2, itemArray3, and the user selects “1,” then itemArray1 should be selected. If 3 is selected, then itemArray3 should be selected. The exact number of lists is configured by a configuration file by the author of the content.

So, you won’t know in advance exactly how many different arrays there need to be.

I ran across this problem while building a javascript-based learning module template where there can be several different versions of each module. All possible page in the module are listed in an array but different audiences will get different subsets of the pages. The content author sets up several versions of the page arrays in the configuration file: pageArray1, pageArray2, etc. A parameter in the launch URL determines which version actually is displayed to the user.

The problem is that I as programmer can not know how many versions will ultimately be used by the authors. If I knew the exact number of different lists, I could write “if else” or “switch” statements for them.

if (userSelection == 3){
     itemArray = itemArray3
    }

Because the exact number of arrays is unknown, it needs to be generated by a statement sort of like this :

var itemArray = pathTo.('itemArray'.+userSelection);

This was my first guess at how to do this, but unfortunately this syntax will not work. But it turns out there is another way to access the identifier of any property of an object: square bracket notation. Dot notation and square-bracket notation are actually parallel means of saying the same thing. According to the comp.lang.javascript FAQ :

//dot notation
var bodyElement = document.body;
 //square bracket notation, using an expression
var bodyElement = document["bo"+"dy"];

So the correct way to write this would be:

var itemArray = pathTo['itemArray'+someOtherVariable]

This way, when your users select which set of items they want to see, the right variable name will be generated automatically.

For more information

Square Bracket Notation