Addings values in an array


#1

I understand that a variable called totalCars lists an array of various values and that .reduce reduces the expression from the many values listed (1car, 2 cars, 3 cars, 4 cars), to one single value (10 cars)

What i do NOT understand is the following:

(add, 0) //why is 'add' listed like that? what is the 0 for?

add(a,b) //what do the a and b represent?

and return a + b. //what do the a b represent?

var totalCars = [1,2,3,4].reduce(add,0);
function add (a,b) {
  return a + b;
}

console.log(totalCars);


#2

Syntax

arr.reduce(callback, [initialValue])

Parameters:
callback - function to execute on each value in the array;
initialValue - value to use as the first argument to the first call of the callback (optional).
So reduce executes the callback function once for each element present in the array.

add(a,b) //what do the a and b represent?

a and b are parameters of add() function.

return a + b;

It means that function add() returns the result value of sum a + b.

This function was created to know for Array.reduce method what should be done for array values. In this case it is a sum of each elements. So instead of for loop we can to use reduce method.

Alternatively can be written:

var totalCars = [0, 1, 2, 3].reduce(function(a, b) {
  return a + b;
}, 0);

// or
var totalCars = [0, 1, 2, 3].reduce((a, b) => a + b, 0);

#3

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