 # Why doesn't the reduce method work when calling an array within a function?

Why doesn't the reduce method work when calling an array within a function?
0

#1

Why doesn’t the reduce method work in the following code? It seems to work when I remove it from the sumAll function and put in an actual array instead, but since arr is an array, I don’t understand why it doesn’t work within the function

``````function sumAll(arr) {
arr.reduce(function(acc, curr) {
return acc += curr;
});

}

sumAll([1, 4]);``````

#2

You need to add a return statement in front of the arr.reduce.

#3

Got it! I’m trying to apply the same logic to this code, but for some reason it returns 1:

``````function sumAll(arr) {

var min = Math.min.apply(null, arr);
var max = Math.max.apply(null, arr);
var all = [];

for (i = min; i <= max; i++) {
all.push(i);
return all.reduce(function(acc, curr) {
return acc += curr;
}, 0);
}
}

sumAll([1, 4]);
``````

#4

Nevermind! Solved it!

``````function sumAll(arr) {
var min = Math.min.apply(null, arr);
var max = Math.max.apply(null, arr);
var all = [];

for (i = min; i <= max; i++) {
all.push(i);
}
return all.reduce(function(acc, curr) {
return acc += curr;
}, 0);
}

sumAll([1, 4]);
``````

#5

Can you tell me why you need to first return all.reduce for it to work, though?

#6

If you want your function to return anything, you must use the return statement to do it.