Search code examples
javascriptsumbreakcontinue

JavaScript Loops Break and continue (JetBrains exercise)


You are given an array of numbers called numbers. Calculate the sum of numbers and return it from the function. If the next number is equal to 0, the program must stop processing the numbers and return the result.

Sample Input 1:**

11 12 15 10 0 100

Sample Output 1:

48

Sample Input 2:

100 0 100

Sample Output 2:

100

I can't get it to work, this is what I've done so far...

Should I create a counter that will sum up every time it goes in the loop (to check if it's a 0) and another one that gets the 'n' value and sums it up the numbers?

function sum(numbers) {
    let add = 0;

    for (let n in numbers) {
        if (numbers[n] === 0) {
            break;
        }
        if (numbers[n] !== 0) {
            add = numbers[n] + n;
            n++;
        }
        return (numbers[n]);
    }
}

Solution

  • I can see multiple problems with your current code. First of all you should name the function in a better way that describes what it actually does. Your for loop does not make sense as with n in numbers you get the elements and not the indexes, so numbers[n] does not make sense. The let in the loop instruction should not be there. The second if block could be an else. add should be set to add + n, the n++ does not make sense. The return should be outside the loop and actually return add.

    It looks like you do not have much experience with how a general program flow looks like, so I would recommend to have a look at the single instructions again. If you know their meaning try to do your algorithm on paper step by step to understand what it actually does vs what it should. You could also add some console.log(...) if you have difficulties understanding the current program flow.