Use of destructuring parameters in reduce method

Hello!

I am reading the book Eloquent Javascript in which I’ve come across a piece of code from the fifth chapter related to the reduce method. Here is the code -

function characterCount(script) {
  return script.ranges.reduce((count, [from, to]) => {
    return count + (to - from);
  }, 0);
}

console.log(SCRIPTS.reduce((a, b) => {
  return characterCount(a) < characterCount(b) ? b : a;
}));
// → {name: "Han", …}

Here in the characterCount function definition he uses destructuring in the parameter list of the reducer function. I don’t understand how it works. I know about the three parameters generally used in the reduce method i.e., accumulator, current value and initial value. Which of these three are the ones inside the square brackets?

Also I went through the documentation on MDN and I found 2 optional parameters for the reduce function - currentIndex and array.

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

I can’t wrap my head around the use of [, index[, array]]. When are these 2 parameters needed?

If your callback function needed to know the index of the item currently being evaluated, or what the original array object being reduced looked like, then you can utilise these parameters with your callback function.

They’re optional because you may not need them. (I don’t have a convenient example of a useful function which uses them, either, but I’m not a frequent JavaScript programmer…)

1 Like

Thanks for the answer. But the question still remains where these parameters need to be used. Why would I need to specify the array inside the callback function even though the reduce method is already working on that array.

Also it’s hard for me to move on without understanding the above code example.

You provide some values to reduce and you receive some values in a callback. All in all you have six different parameters to be concerned about. If you look at mdn’s documentation for array.prototype.reduce then all of those are described and you really really ought to have no issue pointing out which is which.

[].reduce(a, b, c)

function fn(e, f, g) {}

If you do find it difficult to tell which is which, maybe it’s because you define your function within the call to reduce. If you define them separately then you’ll have three in each of those two locations. Which three parameters does reduce have and which three parameters does your callback have?

Your problem is getting lost when looking at the overall thing, but there are several separate parts that you can look at in isolation from one another, and then you should have no problem pointing them out.

Your question title is slightly hinting at the same problem. Destructuring has no special relation to reduce. Two separate things.

2 Likes