How To Break Out Of A For Loop Javascript

In this tutorial, we will learn how to break out of a for loop in JavaScript. Sometimes, you might want to exit a loop before its iteration is complete, such as when a certain condition is met or a specific value is found. JavaScript provides a way to do this using the break statement.

Step 1: Creating a simple for loop

First, let’s create a simple for loop that iterates through an array of numbers.

This code will print out all the elements in the numbers array.

Step 2: Using the break statement

Now, let’s say we want the loop to stop when the value 5 is found. We can do that using the break statement.

When the loop encounters the break statement, it will immediately stop the current iteration and exit the loop. In this example, the output will only show the numbers 1 to 4, because the loop will exit when it reaches the number 5.

Step 3: Using break with labels

In some cases, you might have nested loops, and you might want to break out of more than one loop at a time. JavaScript allows you to do this using labels.

Consider the following example with nested loops:

Full Code:

Output:

1
2
3
4
1
2
3
4

Conclusion

In this tutorial, we learned how to use the break statement to exit a for loop in JavaScript. We also looked at how to break out of nested loops using labels. The break statement can be a useful tool in controlling the flow of your loops and optimizing your code.