Example Of A Memory Leak

Here's a code sample to consider, it is contrived but bear with me:

function someFn(){

var $input = $("<input type='button' />");

$input.appendTo("body");

window.addEventListener('click', function(){

if($input.val() == ""){
// some code goes here
}

}, false);
}

 

If you were to remove $input from the DOM, it would not get garbage collected because the callback for the listener has a handle on it.

 

Likewise, be careful if you do something like this:

function someFn(){

var $someDiv = $("#someDiv");

window.addEventListener('click', function(){

if($someDiv.is(':hidden')){
// some code goes here
}

}, false);
}

 

In this case, if you ever removed $someDiv from the DOM, it would not be garbage collected. So this may be a better solution:

function someFn(){

var $someDiv = $("#someDiv");

window.addEventListener('click', function(){

if($("#someDiv").is(':hidden')){
// some code goes here
}

}, false);
}

 

In the past I would have taken the previous route because I always tried to reduce the amount of times I wrapped something in jQuery, but now I'll have to be careful about what my code is doing. If I never intend to remove $someDiv, then maybe the previous sample is OK, but if there is a possibility that I remove it, then the last sample will avoid a memory leak.