CharlieLily CharlieLily - 14 days ago 5
Javascript Question

Making a sum of arrays stop when the number 13 shows up but still return sum

I am VERY new to Javascript. I tried to look for an answer here but wasn't very lucky and maybe it's how I am asking. So, now I'm posting.

I have a loop in which I am to get a sum of the arrays. However, if the number 13 is in the array, then the loop stops adding numbers together but still return the numbers it added before it got to the 13. Right now, I have this as my code:

function sumNumbers(array) {
var sum = 0;
for(var i = 0; i < array.length; i++) {
sum += array[i];
if(array[i] == 13) {
break;
}
}
return sum;
}


I set the argument for the function which is
'array'
. Then I thought I had to create a variable where the sum of the arrays will appear so I started it at
0
(I did try
[]
but tested it and it wasn't correct - still wanting to understand that). I understand that for any loop, you have to have the initialization which was
i = 0
, then the condition and then the final expression. So, since the number of elements is undefined, I used length. So, it says if the variable i is less than that number then it will keep going and keep adding to it. So I asked it to get a sum of all the arrays but if any number in a array is a
13
, I need it to stop but still return the numbers it added before it reached
13
.

Right now the function is defined, the sum of all arrays are returned and
0
is returned when its empty. But, I get this error


Expected
16
to deeply equal
3
.


and can't figure out what I'm doing wrong. If anyone can help and explain it a little that would be awesome. This is my first question on here, so if I did it in an annoying way, thank you in advance!

Answer

If you need to stop adding when you find 13 and not include 13 in your sum then you need to check on the value of the next array element before you add it to your sum. I reversed two lines in your code. Please see the new version:

function sumNumbers (array) {
  // First check if the array is a valid input to this function
  if (typeof array == 'undefined')
      return 0; // Or even better throw an exception

  var sum = 0;
  for (var i = 0; i < array.length; i++) {
      if (array[i] == 13) { break; }
      sum += array[i];
  }
  return sum;
}
Comments