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)
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
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.

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…

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;
  })
}

Comments

Your Answer

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.