Pitfalls of Remove EventListner in JS

Willson's photo

Published on Jan 15, 2022

1 min read

While addEventlistner function in Javascript gives us a lot of flexibility to deal with Events. So when we need to remove some event listener then we use removeEventlistener function, but there are some common pitfalls which we can be overlooked by us .

So here are some common pitfalls and their workarounds of removeEventlistner:

1) Removing an Anonymous event listener function.



And if we try to remove above eventlistner by below code then it won't be removed :


The reason is because the Functios are refrence types in JS ,So here the functions defined in addEventListner and removeListner are diffrent.

We can overcome this situation by storing the refence of Event listner Function and then using that refrence to add and remove in the addEventListner and removeEventListner. Ex:

function Sayhello()
  alert("Hello there !");


2 ) using bind method:

Since bind method also gives a newly created function so using bind will also not work here. Ex:


If we try to remove above added event listner then it would not be removed as bind has given an new function to execute .

Share this