0

Sometimes I have a callback function where I want to ignore the first argument, but capture the second. How do I write this most eloquently in Javascript? Is there a way to specify in the function declaration that I just want to throw away an argument?

A typical case is when I’m using jQuery’s .each() method to iterate over a bunch of elements in the DOM, but I only care about the second argument given to my callback (element) and I want to ignore the first argument (index).

$(selector).each(function (index, element) {
    // do something with <element> here
    // (but without using <index>)
});

How could I change the above code, so as no not capture index at all?


Some attempts

I have tried using undefined in place of index in my code but (to my surprise!) that resulted in undefined working as a normal variable (with an assigned value) inside my callback function!

function x(undefined) {
    console.log(undefined);
}

x("TEST");  // outputs "TEST" on the console!

I have also tried using true, false or null in my function declaration and results in the more reasonable Uncaught SyntaxError: Unexpected token X (where X is true, false or null) when the function is declared. Why the use of undefined in the function declaration does not result in the same error, is beyond me.

Alex Goncharenko
  • 1,036
  • 2
  • 12
  • 22
zrajm
  • 1,361
  • 1
  • 12
  • 21
  • Not sure whether you are looking for [idiomatic jQuery](https://stackoverflow.com/q/12415451/1048572) or [idiomatic JavaScript](https://stackoverflow.com/q/32197927/1048572)? – Bergi Aug 11 '19 at 18:59
  • Regarding why `undefined` is not a keyword but a valid parameter name, see [here](https://stackoverflow.com/questions/19000087/want-to-know-more-about-undefined) or [there](https://stackoverflow.com/questions/4650442/javascript-function-with-undefined-parameter?noredirect=1&lq=1) – Bergi Aug 11 '19 at 19:04
  • @Bergi I'm looking for idiomatic Javascript case (So your link answers my question!) the fact that I'm using a jQuery method as an example is just incidental. – zrajm Aug 11 '19 at 19:15

0 Answers0