Aaron
Aaron

Reputation: 59

Making a function that adds numbers in an array and returns their sum in javascript

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)

Upvotes: 1

Views: 2064

Answers (3)

KevBot
KevBot

Reputation: 18888

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

Upvotes: 3

isvforall
isvforall

Reputation: 8926

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

Upvotes: 2

Mureinik
Mureinik

Reputation: 311188

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
}

Upvotes: 4

Related Questions