var foo = 0;
var bar = 0;
var arr1 = [1, 2, 3, 4, 5];
var arr2 = [6, 7, 8, 9, 10];
function getSum(arr, sum) {
sum = arr.reduce(function(accum, val) {
return accum += val;
}, 0)
}
getSum(arr1, foo); //expect foo to equal 15, but it stays at 0
getSum(arr2, bar); //expect bar to equal 40, but it stays at 0
I'd like to use this function multiple times, hence the arguments. I know having the sum argument equal Array.reduce() isn't what you're supposed to do, but I'm really not sure what the syntax should be.
Basically I want arr1 values to always be added up for foo, and arr2 always added up for bar, without having to repeat my code.
getSum, it should beundefined, not 0. You also do not havedataanywhere in your code. Fix that toarr, and it works as expected.reduce, pass it as the second parameter (instead of using 0)foo = getSum(arr)sumarg get passed by value, not by reference. this is becausesumis a primitive type (Number).