Checkout my Getting Started with React video course on Skillshare. It is 100% free.

Javascript addEventListener will not duplicate named functions

Let's take the classic use of the anonymous function as an event listener. If we bind the same content multiple times to the same event, then it will be called multiple times.

const getData = () => alert('fetching data from server!')
document.getElementById("anonymous").addEventListener(
  'click', () => getData() );
// it another file from a galaxy far far away
document.getElementById("anonymous").addEventListener(
  'click', () => getData() );

In small codebases, it is easy to avoid this but in large ones, these things can happen.

However, the duplication call will not take place if we use a named function as an event listener.

const myNamedLister = () => getData()
document.getElementById("named").addEventListener(
  'click', myNamedLister );
document.getElementById("named").addEventListener(
  'click', myNamedLister );

Alongside making the code more readable using named functions in addEventListener lister can also protect us from strange bugs in large codebases.

See the Pen
Named functions in addeventlistener
by JS Craft (@js-craft)
on CodePen.

PS: you can also use full Javascript objects with addEventListener.