Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Garbage Collection and jQuery?

How does jQuery (JavaScript) and gc work?

callBack is a function that runs as a callback to a JSON response.

What will be in memory when the callBack function has executed?

What I would like to hear is that the data object and the autoCompleteData will be garbage collected. And only the data stored in $("input#reciever") resides in the memory.

Is this the case?

//The code in question:

var callBack = function(data) {
    var autoCompleteData = jQuery.map(data.receivers, function(receiver, i){
          return {label: receiver.name, id: receiver.id };
    });

    $("input#reciever").autocomplete({
        source: autoCompleteData,
        select: function(event, receiver) {
            $("input#reciever").val(receiver.item.label); 
            $("input#recieverId").val(receiver.item.id);
            return false;
        }

    });
}

1 Answers

Objects are passed by reference in JavaScript, so the object reached by accessing autoCompleteData will be the same one that the autocomplete plugin uses.

Because of this, the variable autoCompleteData will not be garbage collected (but this is not detrimental to your program, as it's required by the autocomplete plugin.

The data object however, should be garbage collected, as nothing is providing a reference to it, and it has fallen out of scope.

Additionally, it is important to note that garbage collection does not work differently for jQuery; it behaves the same as it does across JavaScript (and ofc, all other JavaScript frameworks).

like image 106
Matt Avatar answered Apr 08 '26 05:04

Matt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!