Using Break and Continue in JavaScript Loops

Break and continue are two keywords you can use in JavaScript 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 JavaScript loops

We will start by looking at how we can use break with the various loops.

1. Using break in a for loop

In a for loop we iterate a given number of times. We can use a break statement to stop iterating at a point before we would normally finish.

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.

Here is an example where we break out of the loop when we find what we are looking for.

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 statement 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.

2. 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++;
}

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.

Essentially, a break statement in a for and while loop accomplish the same thing. Now lets look at what happens if we try to do it in a foreach loop.

3. Using break in a foreach loop – You can’t

You can’t use a break statement in a foreach loop with JavaScript. 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.

Here is an example of how we can throw an error in order to break out of a foreach loop.

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 if you want to handle unexpected errors gracefully, but using it simply to be able to break out of the loop is not a good idea.

I challenge you to try and see what happens if you replace the ‘throw “break ‘ statement with a break statement. Simply copy and pate the code into the console and make the changes there.

How to use continue in JavaScript loops

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.

1. 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.

2. Using continue in a while 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.

3. Using continue in a foreach loop – You can’t

As with the break statement, a continue keyword will not work inside a JavaScript 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.

Should you use Break and Continue at all?

In my opinion it is completely fine to use both break and continue. They have been put into the language because they are useful.

The main thing you should be concerned about is that the code is readable and that it makes sense to use it. If you are using a foreach loop for example I dont think it makes sense because you have to create a work-around that makes it harder to read. In that case you should simply switch to some other loop instead.

Another example of when it would be a good option to use one of them is if you have a lot of work in each iteration and you don’t have to perform all the work if certain conditions are met. For example, you are looking for the first instance of a certain word. Once you find the work you can break out of the loop if you are done, or you can use the continue keyword if you need to look at more arrays or whatever your use case is.

Applications Using These Techniques

Let’s build a few small applications to illustrate one of the break examples and one of the continue examples.

1. Example Application Using Continue in a JS loop

Using the continue keyword is quite common if you want to skip the rest of the loop because you know you don’t have to perform the work. In this example we will have a function that will take in an array of names, but we only want to do the work inside the function if the name starts with a specified letter. If it does not, then we just want to go on to the next name in the array.

The words in the array will be first name and last name separated by a comma. Our job in this function is to remove the comma and create a new array with the names without commas. You should also check out this guide on how to remove commas to see different ways to do it.

Lets start by creating an example array that contains names.

var names = ["John, Bush", "All, Piper", "Tina, Frey", "Mike, Eagle", "Fred, Turner"];

Now lets create a function that will do our work.

function processNames(names, letter){
    var newArray = [];

    for(var i = 0; i < names.length; i++){
        if(names[i].charAt(0) != letter)
        {
            continue;
        }
        newArray.push(removeComma(names[i]));
        // More work here
        // If it is this short you could just check for 
        // equality and do the work inside the if statement.
        // But if there is more work then a continue statement might make sense. 
    }

    return newArray;
}

function removeComma(string){
    return string.replace(",", "");
}

And that is it. This is not an amazing example because you could simply do the work inside the conditional statement, but if you wanted to do a lot more processing of the name then is when the continue keyword becomes more useful. This function is case sensitive, if you want it to treat ‘A’ and ‘a’ the same then you can check out the guide on how to use .toUpperCase() here. toUpperCase is not the most common way to do it but the guide goes into an example of how you can treat comparison and ignore the case of the letter/word.

var test = processNames(names, "A");
test // gives you ["All Piper"]

2. Example Application Using Break in a JS loop

A classic example is searching for something and then ending the loop if you find it, but we already did that example when we went over the break statement. In this application we are going to use the break statement when we know that what we are looking for is not true.

We will create a function that takes in an array of arrays. Each array contains a series of numbers and we want to make sure they are all even. For all the arrays inside the array we get we have to loop over all the numbers. If one of the arrays contain a number that is odd then we want to mark it as false. We are going to return an array where each index represents if the input array contained all even numbers or not.

We will create a function that will check if all the numbers given to it in an array are even. If there are 1 million numbers, and the first number is odd, then we don’t want to check the remanding as it is unnecessary work. We will then simply use the break keyword to stop looping and return false.

Lets start by creating three arrays that are filled with numbers. We will then add these three to a final array that we will pass to our method.

var arrayOne = [2,4,6,8,10,12,14,16,18,20];
var arrayTwo = [20,18,16,14,12,10,8,6,4,2];
var arrayThree = [1,4,6,8,10,12,14,16,18,20]; // First element is odd
var arrayOfArrays = [arrayOne, arrayTwo, arrayThree];

Now lets create our function that will do our work for us.

function processArrays(arrayOfArrays){
    var result = [];
    var temp = true;

    for(var i = 0; i < arrayOfArrays.length; i++){
        temp = true;
        for(var j = 0; j < arrayOfArrays[i].length; j++){
            if(arrayOfArrays[i][j] % 2 != 0) {
                temp = false;
                break; // Break as we don't need to look at the rest
            }
        }

        result.push(temp);
    }

    return result;
}

If the arrays contained millions of numbers then using the break statement to prevent us from evaluating all the numbers when we know it will be false the second we find the first odd number can save us a lot of work.

You should now be equipped with everything you need to work with break and continue statements in JavaScript.

Last Updated: by Ole