j.doe
j.doe

Reputation: 1254

Unable to assign value to global array without using .push()

For some reason I cannot assign anything to a global array without using .push().

(function() {
    var globalEmail = [];

    var testClear = function() {
        var arr = [1, 2, 3];

        if (globalEmail.length > 1) {
            globalEmail = [];
        }
        else {
            globalEmail = arr;
        }
    };

    window.globalEmail = globalEmail;
    window.testClear = testClear;
})();

If I call testClear() and then globalEmail in the console, globalEmail remains unchanged.

Upvotes: 2

Views: 221

Answers (3)

Alexis Wilke
Alexis Wilke

Reputation: 20731

You want to define the globalEmail variable as global, not local.

(function() {
    window.globalEmail = []; // this goes here

    var testClear = function() {
        var arr = [1, 2, 3];

        if (window.globalEmail.length > 1) {
            window.globalEmail = [];
        }
        else {
            window.globalEmail = arr;
        }
    };

    //window.globalEmail = globalEmail; <-- not here
    window.testClear = testClear;
})();

The window. is not absolutely required, but the var globalEmail; within a function defines a local variable, which is not what you wanted in the first place.

Although, if the point of testClear() is to clear any array, then it is not properly implemented. Instead it should take a parameter and you work on that parameter.

function testClear(a)
{
    var arr = [1, 2, 3];

    if(a.length > 1) {
        a.splice(0);
    }
    else {
        a.splice(0);
        a.push.apply(a, arr);
    }
}

testClear(window.globalEmail);

Then the testClear() function makes more sense, I think.

Note that there are drawbacks with a.push.apply() which breaks on large arrays. See here How to extend an existing JavaScript array with another array, without creating a new array? for details.

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386604

For empty an array, you could set the lenght to zero and for assigning, you could use Array#push with spread syntax ...

var globalEmail = [],
    testClear = function() {
        var arr = [1, 2, 3];

        if (globalEmail.length > 1) {
            globalEmail.length = 0;
        } else {
            globalEmail.push(...arr);
        }
    };

testClear();
console.log(globalEmail);

testClear();
console.log(globalEmail);

Upvotes: 2

kLabz
kLabz

Reputation: 1847

As said in comments, you are loosing references here because you assign globalEmail to new arrays, so window.globalEmail is different than the new globalEmail array.

You need to modify the array in place (with splice and concat, for your example).

Upvotes: 1

Related Questions