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])
3

3 Answers 3

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) => {})
Sign up to request clarification or add additional context in comments.

Comments

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) {
}

Comments

0

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

1 Comment

Hey @smuggledpancakes, please upvote and accept my answer if it was helpful

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.