Using Break and Continue in JavaScript Loops

Break and continue are two keywords you can use in loops. Break will “break” you out of the loop, i.e. you will stop iterating through the loop. Continue on the other hand will skip the rest of the loop and continue with the next iteration. In this post we will look at how we can use both break and continue with for loops, while loops, and foreach loops.

How to use break in a JavaScript loop


Using break in a for loop

First we will look at a for loop. In a for loop we iterate a given amount of times. We can use a break statement to stop that loop at some point. A common use case is that you loop over an array, and when you find what you are looking for you use the break statement to stop. If you have already found what you are looking for then there is no need to loop any further.

var names = ["Using", "break", "in", "JavaScript"];
var wordWeAreLookingFor = "break";

for(var i = 0; i < names.length; i++){
    console.log(i);
    if(names[i] == wordWeAreLookingFor){
        break;
    }
}

In the example above there are 4 words in the names array. As we loop over the array we print out the value at each index. Without the break statement we would be looping over all the words, but since we do have the break statement we will stop when we find the word “break”. When the break keyword is run we will “break” out of the loop and the code would continue on the line after the loop. You can copy the example above into the console and try searching for a different word and you can explore what happens when you change it.

Using break in a while loop

Using a a break statement in a while loop works the same way as it does in a for loop. If we encounter the break keyword we will simply stop looping and we will continue on the line after the loop.

var names = ["lets", "try", "how", "a", "while", "loop"];
var wordWeAreLookingFor = "while";
var i = 0;

while(i < names.length){
    console.log(i);
    if(names[i] == wordWeAreLookingFor){
        break;
        console.log("This is right after the break statement");
    }
    i++;
}

Now in this example we are trying to print a statement right after the break keyword to show that we won’t actually execute that line of code. If you run the example above in the console you can see that it will print the numbers 0-4, where 4 is the index where we find the word we are looking for.

Using break in a foreach loop – You can’t

You can’t use a break statement in a foreach loop. That being said, there are ways of exiting a foreach loop if you really want to. You can throw an error and then catch the error outside. There is no reason to use a foreach loop if you want to use break with it. You can use a for or a while loop instead. You can also use a “.some” instead of “.forEach”.

var names = ["lets", "try", "how", "a", "while", "loop"];
var wordWeAreLookingFor = "while";

try{
    names.forEach(function(element, index){
        console.log(element);
        if(element == wordWeAreLookingFor) {
            console.log(index);
            throw "Break";
            console.log("This is right after the break statement");
        }
    });
} 
catch(exception){
    console.log(exception);
}

In the example above we use a work around in order to exit the foreach loop. I don’t advise that you do this and I recommend that you use a different kind of loop instead. Using try catch blocks is something that you should get used to though if you want to handle unexpected errors gracefully.

How to use continue in a JavaScript loop

The continue keyword is a bit different than the break keyword. Continue will allow us to skip the rest of the code inside the loop and immediately start the next iteration. This can be quite useful is some cases where we want to save doing a bunch of work if we don’t have to.

Using continue in a for loop

var names = ["Using", "continue", "in", "JavaScript"];
var wordWeAreLookingFor = "continue";

for(var i = 0; i < names.length; i++){
    if(names[i] == wordWeAreLookingFor)
    {
        continue;
    }
    console.log("This is index number: " + i)
}

In the example above we use the continue keyword if we find the word we are looking for. That means that if we find the word “continue” we will skip the rest of the loop, i.e. we won’t print the index number to the console. If you run the example in the console you can see that we do not print index number 1.

Using continue in a for loop

Continue in a for loop works pretty much the same as in a for loop.

var names = ["Using", "continue", "in", "JavaScript"];
var wordWeAreLookingFor = "continue";
var i = 0;

while(i < names.length){
    if(names[i] == wordWeAreLookingFor)
    {
        i++;
        continue;
    }
 
    console.log("This is index number: " + i)
    i++;
}

The only thing to be careful with when using a while loop is the condition for breaking the loop. In this case we are using an incrementor, and we have to be careful to increment it or else we could get an infinite loop. Notice how we also increment the “i” inside the if statement just before the continue keyword. This is because it would have kept “continuing”/jumping to the next iteration of the loop and never have incremented i, meaning we would continue to continue until the browser crashes. If you try it without the incrementor inside the if statement it might crash your browser, it did so for mine.

Using continue in a foreach loop – You can’t

As with the break statement, a continue keyword will not work inside a foreach loop. There is a way around it though and that is to use the return keyword. As you are passing a function to the foreach function, a return keyword will effectively stop the execution of the method and it will continue on the next iteration. As with break statement though, you are probably better off using some other loop if you want to use the continue keyword.

var names = ["lets", "try", "how", "a", "while", "loop"];
var wordWeAreLookingFor = "while";

names.forEach(function(element, index){
    if(element == wordWeAreLookingFor){
    return;
}

console.log("This is element: " + element + ", in index: " + index);
});

In the example above it will skip index 4 because we used the return keyword. As with the break statement, we can only emulate the effect.

. If you want to read more about JavaScript you can have a look at how to create a class in JavaScript.