I can't see why this function is returning undefined:
function sumArray(array) {
array.reduce(function(result, item) {
return result + item;
})
}
array = [1,2,3]
sumArray(array)
I've tried something similar and it works ok (below), so I'm not sure if it's specific to the parameter being an array?
function sayNumber(num) {
return num + 1;
}
num = 1
sayNumber(num)
4 Answers 4
What you actually need is to add one more return statement.
function sumArray(array) {
//here
return array.reduce(function(result, item) {
return result + item;
});
}
array = [1,2,3];
sumArray(array);
//6
1 Comment
The function sumArray is not returning the result from array.reduce. Insert a return before your array.reduce.
Comments
It returns undefined because there is no return statement for the sumArray function.
(The anonymous function you pass to reduce has one, but that is a different function).
If you want to return the result of calling array.reduce when you have to say so explicitly:
return array.reduce(etc, etc...
Comments
You should return the value of the function sumArray Like this:
function sumArray(array) {
return array.reduce(function(result, item) {
return result + item;
})
}
sumArraydoesn't return anything.