Skipping parameters in callback function

I acknowledge that using _ is a common pattern to omit parameters that prepend the one you want. That's cool for one parameter, maybe 2.

somethingWithACallback((_, whatIAmLookingFor) => { 
  // ...
})

but I got stuck needing the 5th one. This would mead I'd have to write

somethingWithACallback((_, __, ___, ____, whatIAmLookingFor) => { 
  // ...
})

For that case I propose this pattern:

somethingWithACallback((...args) => { 
  const whatIAmLookingFor = args[4];
})

With destructuring, you can also do this

somethingWithACallback((...args) => { 
  const [,,,,whatIAmLookingFor] = args;
})

and apply that to multiple parameters

somethingWithACallback((...args) => { 
  const [,,,,whatIAmLookingFor,,andAnotherThing] = args;
})

and thereby essentially pick what you need.


The technique is not pretty, but I use it myself on several occasions. I guess it is still quite better to give those unused arguments meaningful names (just to avoid confusion), but you're fine in using underscores.

I often see it used in jQuery related callbacks, where the index is often passed in as first argument, like

$('.foo').each(function(_, node) {
});

because most of the time, you don't care about the index there. So to answer your actual question, there is nothing wrong in using the technique (beside confusion maybe) and there is no better/cleaner way to skip unwanted arguments.