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)
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)
Share
Improve this question
edited Jun 21, 2016 at 19:39
Peter Gordon
1,0771 gold badge18 silver badges40 bronze badges
asked Jun 21, 2016 at 19:30
AaronAaron
591 gold badge1 silver badge4 bronze badges
7
- You seem to be missing some code – theblindprophet Commented Jun 21, 2016 at 19:32
- oops sorry. Here is the missing code: – Aaron Commented Jun 21, 2016 at 19:34
- 2 It's because your return is RIGHT in the for. So, it runs once, and returns. Boom. done. Move that return outside the FOR loop. – durbnpoisn Commented Jun 21, 2016 at 19:34
- 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) – Aaron Commented Jun 21, 2016 at 19:34
- 1 return statement is the culprit here :) – Azim Commented Jun 21, 2016 at 19:40
3 Answers
Reset to default 4You 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 plete, 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
}
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));
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));