1

I'm trying to create a function that will add the numbers in an array and return their sum. For some reason it's returning 1 instead of 15 and I'm not sure why.

var myArray = [1,2,3,4,5];  
function addThemUp(myArray) {
    var arrayTotal = myArray.length; 
    var totalSum = 0;

    for(var x = 0; x <arrayTotal; x++) {
        totalSum += myArray[x];
        return(totalSum)
    }
}

addThemUp(myArray)
Peter Gordon
  • 1,075
  • 1
  • 18
  • 38
Aaron
  • 49
  • 1
  • 1
  • 4

3 Answers3

4

You placed the return statement inside the loop, so it will sum the first element only and then return. Instead, you should allow the loop to complete, and return the sum only after its done:

function addThemUp (myArray) {

    var arrayTotal = myArray.length; 
    var totalSum = 0;

    for(var x = 0; x < arrayTotal; x++){
        totalSum += myArray[x];
    }

    return(totalSum); // This is where the return should be
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
3

In your case, you need to fix where the return of totalSum is, to be the last statement of your function (after the loop).

That being said, you may find that adding up all the numbers in an array is much cleaner and simpler to do with reduce:

function addThemUp(myArray) {
  return myArray.reduce(function(a, b) { return a + b; });
}

var myArray = [1, 2, 3, 4, 5];
console.log(addThemUp(myArray));
KevBot
  • 17,900
  • 5
  • 50
  • 68
2

You should return sum after for loop

var myArray = [1, 2, 3, 4, 5];

function addThemUp(myArray) {

    var arrayTotal = myArray.length;
    var totalSum = 0;

    for (var x = 0; x < arrayTotal; x++) {
        totalSum += myArray[x];
    }
    return totalSum;
}

console.log("Sum of all elements: " + addThemUp(myArray));
Azim
  • 1,043
  • 13
  • 27
isvforall
  • 8,768
  • 6
  • 35
  • 50