Nekkoru Nekkoru - 1 month ago 5x
Javascript Question

Javascript - Array.prototype.forEach() - are the three arguments necessary?

Mozilla's Developer Network states:

[the forEach callback] is invoked with three arguments:

  • the element value

  • the element index

  • the array being traversed

However, this is a little unclear to me. Are all three of these arguments necessary? The specific callback I'm writing will not use any of those values. Do I declare them anyway, or can I safely skip them?


You can safely skip them.

You never HAVE to declare function arguments. Often, values will be passed to callbacks whether or not you've prepared the callbacks to receive them - it matters only if your function needs to make use of those arguments.

An example is any event callback, e.g., to which the event object - reporting about what happened - is always passed as the first argument.

foo.addEventListener('click', function(evt) {
    //if I never reference the evt object, I need not define the evt argument
}, false);