Zollie
Zollie

Reputation: 380

How do JavaScript's higher order functions interpret callback function parameters?

I've been using higher order functions with some success, but I'm a bit confused about how callback parameters work. Reduce, for example, has a few parameters (accumulator, currentValue, etc.). Naming doesn't seem to matter. I can swap out the use of accumulator with 'acc' if need be or replace it with a completely different word. That leads me to believe reduce interprets parameters by the order they are given. Is that correct?

If so, how do I indicate that I only need to use a parameter later in the list? Let's say I only intend on using currentIndex. Would I need to enter parameter values for the two before currentIndex (accumulator and currentValue) even though I'm not using them?

Upvotes: 0

Views: 154

Answers (1)

philip yoo
philip yoo

Reputation: 2512

That leads me to believe reduce interprets parameters by the order they are given. Is that correct?

Yes, the order of the arguments is what matters, naming doesn't matter, besides the fact that the name might help you better identify the purpose of the argument.

If so, how do I indicate that I only need to use a parameter later in the list? Let's say I only intend on using currentIndex. Would I need to enter parameter values for the two before currentIndex (accumulator and currentValue) even though I'm not using them?

Yes, you'll need to enter all parameter names to "reach" the parameter you want.

You don't necessarily have to use those params. For example:

function hello () {
  return "hi"
}

console.log([1, 2, 3, 4].reduce(hello))   // prints "hi"

Silly example, but I want to show that I'm not actually using any of the reduce functions params and just returning whatever I want. This still works, but obviously defeats the purpose of using the reduce function.

Thanks to @andrew-li , if you don't plan on using a given param at all, name the variable something that would easily determine it is an unused variable:

function hello (dummy1, dummy2, cidx) {
  return cidx
}

console.log([1, 2, 3, 4].reduce(hello))   // 4

Upvotes: 2

Related Questions