One of the bad JavaScript programming practice is creating large number of global variables. In javascript dynamic memory(or objects) are removed from memory by the garbage collector when their variable scope ends or are dereferenced. Scope of global variable never ends therefore they remain in memory throughout the execution of the page even if they are not needed. This scenario creates memory leakage(unused objects remaining in memory).
There are basically two solutions to this problem: Use function scope or else dereference them manually.
JavaScript has no local scope. Local scope has been introduced in JavaScript 1.6 but thats not yet been implemented by any browsers yet. So use function scope to create variable so that variables are deleted when the function ends.
Instead of
var object2 = {};
Use
var object1 = {};
var object2 = {};
})(window, document);
In the above example I used Immediately-Invoked Function Expression.
The second method is to dereference the objects manually therefore garbage collection deletes objects that are not referenced by any variables.
var object2 = {};
object1 = null;//object removed from memory
object2 = null;//object removed from memory
Here remember that object is removed from dynamic memory but the variables is still there on the stack i.e., pointing to the null object.
If you have too many global variables and you want to dereference by yourself then you can do this:
for(var x = 0; x < array.length; x++)
{
array[x] = null;//clean all objects
}
“delete” operator
“delete” operator can only dereference object properties not variables(global or function scope) i.e., anything declared using “var” keyword cannot be dereferenced using “delete” operator.
Although we can access global variables using window object, they are not considered as properties of global object therefore we cannot deference them using “delete” operator.