0

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)
asked Oct 29, 2017 at 14:02
2
  • 2
    Because your function sumArray doesn't return anything. Commented Oct 29, 2017 at 14:03
  • Any function that doesn't explicitly return something returns "undefined" instead. You just invoke the array.reduce method but your not returning it so it really doesn't have anything to return Commented Oct 29, 2017 at 14:05

4 Answers 4

2

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
answered Oct 29, 2017 at 14:04
Sign up to request clarification or add additional context in comments.

1 Comment

@safikabis, happy to help and welcome to Stack Overflow! If this or any other answer solved your problem, please, mark it as accepted.
0

The function sumArray is not returning the result from array.reduce. Insert a return before your array.reduce.

answered Oct 29, 2017 at 14:04

Comments

0

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...
answered Oct 29, 2017 at 14:04

Comments

0

You should return the value of the function sumArray Like this:

function sumArray(array) {
 return array.reduce(function(result, item) {
 return result + item;
 })
}
answered Oct 29, 2017 at 14:09

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.