John Fred John Fred - 1 year ago 61
Javascript Question

Is there something wrong with using window['variableAsString']?

It's been very useful for writing functions that require iterating through variables, but I've heard users advising against using similar methods.

Is there something wrong with writing code this way?

Example of use:

Say I have three arrays and want to add a value to all three:


for (var i=1;i< 4; i++){

Answer Source

If you're going to need to iterate through a set of variables, plan ahead and put them inside an object:

var myArrays = {
    array1: [],
    array2: [1, 2],
    array3: [4, 4],
    "any-name-you-want-works": []

Accessing them is still straightforward:


Adding a new array to myArrays:

myArrays.array4 = [3, 5];

And iterating is made easy (this is the recommended way):

for (var arr in myArrays) {
    if (object.hasOwnProperty(arr)) {

If you don't need to support old browsers, you can use newer features as well (source):

Object.keys(myArrays).forEach(function(key, index) {

More info on Object.keys().

Then, if you're using a popular lib like underscore or lodash, you can do lots of thing easily on objects and arrays:

    .each(function(arr) { arr.push(1) }) // adds one to each array
    .first() // takes the first array
    .map(function(val) { return val *2; }) // and multiply each value
    .reverse() // then reverse those values
    .value(); // and get the array

As I mentioned in a comment, you shouldn't pollute the global window object and also iterate through it to avoid collision or unexpected behaviors.

Wrapping your code inside an IIFE (Immediatly-Invoked Function Expression) is always a good idea, instead of using the global scope, for multiple reasons, but that's a whole other discussion and we can achieve what you want without it (for this question anyway).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download