user3064776
user3064776

Reputation: 119

Javascript: Is it appropriate to use a global variable?

So I have multiple different functions - let's call them function A, B, C, ..., Z. Let's call function A the "start state" while function Z the "end state".

I also have an array for which only function A uses to choose an index to pass to later functions for use. All later functions do not use the array, only just the index.

However, after function Z, it needs to remove that index from the array and return back to A. Once again, A will choose an index from the same array, but this time the array has one less index in it.

Without global variables, that means I would have to pass the array as an argument from A to Z, even though B to Y will not even touch the array.

Code-wise example:

function A() {
    var arr = [4, 1, 2, 5];  // Some array
    var ind = arr[0];        // Some index

    // Pass index and array to B
    B(ind, arr);
}

function B(index, array) {
    // B will do some stuff with index 
    C(index, array);
}

function C(index, array) {
    // C will do some stuff with index 
    D(index, array);
}

// ...
// Repeat until Z
// ...

function Z(index, array) {
    // Remove it
    array.splice(0,1);

    // Go back to A() again
    A();
}

This looks tacky and it doesn't make much sense to me to do something like that. Would it be appropriate to just use a global variable in this case? If not, what's a better option to accomplish the above without unnecessary passing of arguments?

Upvotes: 1

Views: 121

Answers (1)

Just create a closure:

(function() {
    var pseudoGlobalArray = [];

    function A() {
        pseudoGlobalArray[0] = 42; // OK
    }

    function B() {
        pseudoGlobalArray[1] = 43; // OK
    }
}());

pseudoGlobalArray[2] = 44; // don't do this, array not even visible here

Upvotes: 2

Related Questions