Help with the Reduce function

Tell us what’s happening:
Hi

I changed the code here from:
args.reduce((a, b) => a+b);
to:
args.reduce((a, b) => a-b);
However when I pass the value 1 and 2 in sum I get -3.

How is the code passing these values to get -3?

I’m trying to get grips with lesson before I move on.

Your code so far


const sum = (...args) => 

args.reduce((a, b) => a - b, 0);
console.log(sum(1,2))

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36 Edg/89.0.774.75.

Challenge: Use the Rest Parameter with Function Parameters

Link to the challenge:

Hi @jonnyd83

.reduce is doing the following:

  1. For the first argument, 1, the callback is invoked with a = 0 and b = 1 it subtracts 0 - 1 which is -1.
  2. For the second argument, 2, the callback is invoked with a = -1, the value returned from the previous call and b = 2. It subtracts -1 - 2 which becomes -3 and it returns -3 because there are only two values passed. Try passing more values and see what it returns.

I hope that is helpful. For more about .reduce, you can also read the docs at MDN.

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

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.