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.