Referring to Anonymous Functions by Name

JavaScript Quick Tips

Occasionally you may find yourself needing to refer to an anonymous JavaScript function by name. That sounds like a contradiction in terms so let me explain what I mean.

You’re probably used to defining anonymous functions; it’s hard to avoid it in web development. The common case is providing an event handler or maybe a function to process a single element in Array.forEach.

element.addEventListener('myEvent', function() {
  console.log("Got it!");

In these cases the callee gets a reference to the function in order to invoke it and that’s all that’s required. If the caller needs a reference to it for some reason it can store it as a variable prior to passing it.

var myHandler = function() {
element.addEventListener('myEvent', myHandler);

// now use myHandler again somewhere ...

But what if the anonymous function needs to refer to itself for some reason? Perhaps for example you only want an event listener to be fired once and then be removed. How would you do that if you don’t control the code that calls your function?

Turns out it’s quite simple. You can give your “anonymous” function a name when you pass it in. That name is still in scope within your function which allows it to refer to itself. So here’s how your event listener can remove itself.

element.addEventListerner('event', function handler() {
  console.log("Event happened!");
  element.removeEventListener(handler); // Remove thyself

The only difference to our first example is that we’ve given our function a name handler with which it can refer to itself within its own body.

You won’t need this very often but when you do it’s very handy.