I don't understand the concept

Tell us what’s happening:
I don’t understand the concept of reduce().

Someone can help me ?

Your code so far


const sum = (...args) => {
return args.reduce((a, b) => a + b, 0);
}
console.log(sum(1, 2, 3)); // 6

Your browser information:

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

Challenge: Use the Rest Parameter with Function Parameters

Link to the challenge:

Hii, reduce method can be a little confusing at first, but the basic idea is very simple. It takes a number of arguments and produces a single output. For example as in the above challenge. the rest parameter grabs a number of arguments passed to the function. Lets say 3 arguments were passed. the rest parameter (...args) stores it in an array named args. so when we apply reduce method to this array, args.reduce((a, b) => a + b, 0) as you can see a ‘0’ has been provided as the initial value, so ‘a’ stores ‘0’ as the initial value. ‘b’ stores the first element of the array. The reduce method has been defined to find the sum. so ‘a’ and ‘b’ gets added and the value is stored in ‘a’. then ‘b’ stores the second element of the array and again the whole process is repeated. the value is again stored in ‘a’ and ‘b’ stores the next value of the array. This is how reduce method works. Also, note that the reduce method can take up to 4 arguments. but in this example for keeping it simple, we have only provided 2 arguments. the first that is ‘a’ is called an accumulator. and ‘b’ is the current value.

Hope that helps.

Thank you for your halp hrs070

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