I can't understand this

Please can you help me understand the .reduce iterator method of JavaScript?

As I understand it, the .reduce() function takes a type of function, which you must write, and takes the values in the list to provide one value. Take the following example:

const exampleFunc = (startingVal, indexVal) => startingVal + indexVal
const arr1 = [1, 2, 3, 4, 5, 6];
console.log(arr1.reduce(exampleFunc));
//you would get an output of 21

This code could be replicated with the following code, it is just shorter (an I think you can do more with .reduce(), although I haven’t used it much myself):

arr1 = [1,2,3,4,5,6];
let startingVal = 0;
for (let indexVal = 0; indexVal < arr1.length; indexVal++){
startingVal += arr1[indexVal];
}
console.log(startingVal);
//should give 21

Here is a good article (MDN docs)on it.

I hope this helps!

1 Like

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