1

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

arr.reduce(callback( accumulator, currentValue, [, index[, array]] )[, initialValue])

The index and array syntax confuses me. It looks like they are both optional, but is it required that you use index if you want to use array? Why is the syntax not laid out like this:

 arr.reduce(callback( accumulator, currentValue, [, index], [, array] )[, initialValue])
smuggledPancakes
  • 9,881
  • 20
  • 74
  • 113
  • If you need another example here it is https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify – lastr2d2 Dec 23 '20 at 01:24
  • Parameters are passed by order, not name, so if you want to pass a value to *array* as the 4th parameter, there must be values at positions 1, 2 and 3. – RobG Dec 23 '20 at 01:46
  • Probably a duplicate of [*How do optional parameters in Javascript work?*](https://stackoverflow.com/questions/38926848/how-do-optional-parameters-in-javascript-work) – RobG Dec 23 '20 at 01:48

3 Answers3

1

It looks like they are both optional, but is it required that you use index if you want to use array?

Yes, this is a requirement. JavaScript doesn't have named parameters, so you can't "skip" certain arguments (there are workarounds for this, but this requires modification on both the function definition and the caller). You don't have to use the index argument per se in your function callbacks body, its more that it needs to supplied in the callback function's parameter list so that you can access the subsequent parameters (such as the array). Typically when you want to "skip" and argument you could use an underscore:

arr.reduce((accumulator, currentValue, _, array) => {})
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
0

In JavaScript You can't just skip the argument. The following code just won't compile:

myFunction(1,2, , 3);

Thus, if You want yo provide argument N - You definitely need to provide argument N-1. Even if You want to pass undefined You need to do this explicitly:

myFunction(1,2, undefined, 3);

The same is for the arguments in function signature. You can't miss them, but You may put some placeholders to make things work:

function f(a, b, junk, d) {
}
0

Because if you need to have an array, you HAVE to name index. You cannot request an array but skip index.

IvanD
  • 2,728
  • 14
  • 26