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.