CharlieLily - 14 days ago 5

Javascript Question

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'`

`0`

`[]`

`i = 0`

`13`

`13`

Right now the function is defined, the sum of all arrays are returned and

`0`

Expectedto deeply equal`16`

.`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;
}
```

Source (Stackoverflow)

Comments