Remove event listener using an arrow function

Let's assume that you set the following listener with an anonymous arrow function:

javascript
window.addEventListener('click', () => alert('You clicked'));

If you try to remove the listener, you can't reference the anonymous function:

javascript
window.removeEventListener('click', /* Name of function? */); // Error

So you should declare it first:

javascript
const f = () => alert('You clicked');

window.addEventListener('click', f);
window.removeEventListener('click', f);

Which is the same as:

javascript
window.addEventListener('click', f = () => alert('You clicked', f));
window.removeEventListener('click', f);

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.