An interesting tidbit I stumbled upon recently is the ability to remove an event listener once it’s called.

In the past, I would have added an event listener to an element and then removed it within the callback function. It would have looked something like this:

JavaScript

const button = document.querySelector("button");

button.addEventListener("click", function onClick() {
  console.log("clicked");
  button.removeEventListener("click", onClick);
});

In this example, an event listener is attached to the button element, and once clicked, the listener is removed.

This code can be cleaned up by passing one additional argument to the event listener, { once: true }.

JavaScript

const button = document.querySelector("button");

button.addEventListener(
  "click",
  function onClick() {
    console.log("clicked");
  },
  { once: true },
);

This example works exactly like the one above, except it requires less code. Less code means fewer potential bugs to fix later 😁.