John
John

Reputation: 381

Javascript event handler Garbage collection

Will below code result in memory leak? When I remove 'submitBtn' from DOM, will it be garbage collected along with it's event handler? Or Do I have to call removeEventListener() before I remove 'submitBtn' from DOM?

function addEventHandler() {
  var btnId3 = document.getElementById("id3");
  btnId3.addEventListener(
    "click",
    function () {
      console.log(btnId3.name);
    },
    false
  );
}

addEventHandler();
document.forms[0].lastElementChild.remove();
<!DOCTYPE html>
<html>
<head>
  <title>JS GC</title>
</head>
<body>
  <form id="id1" method="post">
    <input id="id2" type="text" name="username" value="John">
    <input id="id3" type="button" name="submitBtn" value="Echo Username">
  </form>
</body>
</html>

Upvotes: 1

Views: 136

Answers (1)

Jonas Wilms
Jonas Wilms

Reputation: 138537

Every value (including functions and DOM objects) is viable for garbage collection when all references to it are lost. If you remove a DOM node, it gets detached from the DOM tree, and thus the one reference to it gets removed. As long as there is no other reference to it (which you don't have in your code), the node is viable for garbage collection. Therefore also the function (if it is only referenced inside the node) is viable for gc too.

Upvotes: 1

Related Questions