A partial archive of discourse.wicg.io as of Saturday February 24, 2024.

Named arrow functions


Named functions are practical to reference the function itself inside the function body. I use them mainly in two cases:

  • Recursive setTimeout (a trick to do a proper setInterval which automatically stops when an exception occurs)
  • Trigger an event listener just once

For the second, just consider this example:

var obj = {
    listen_once: function() {
        let self = this;
        this.elem.addEventListener("click", function onFirstClick(ev) {
              self.elem.removeEventLisnener("click", onFirstClick);
              // ...
   // ...

That’s a pity! Because arrow functions aims at getting rid of the let self = this; (or the Function.prototype.bind()) trick.

How about allowing naming arrow functions:

this.elem.addEventListener("click", onFirstClick(ev) => {
    this.elem.removeEventListener("click", onFirstClick);
   // ...

Note: I see that it has been deferred in the EcmaScript wiki page. Any reason for that? I write this post to stress how useful it would be to have named arrow functions.



This is one of the crucial things missing from arrow functions. But as I think that arrow functions were meant to be concise, so they excluded naming them explicitly.