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.
1 2 3 4 5 |
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; for (let i = 0; i < numbers.length; i++) { console.log(numbers[i]); } |
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.
1 2 3 4 5 6 |
for (let i = 0; i < numbers.length; i++) { if (numbers[i] === 5) { break; } console.log(numbers[i]); } |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
let matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]; outerLoop: for (let i = 0; i < matrix.length; i++) { for (let j = 0; j < matrix[i].length; j++) { if (matrix[i][j] === 5) { break outerLoop; } console.log(matrix[i][j]); } |
Full Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; for (let i = 0; i < numbers.length; i++) { if (numbers[i] === 5) { break; } console.log(numbers[i]); } let matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]; outerLoop: for (let i = 0; i < matrix.length; i++) { for (let j = 0; j < matrix[i].length; j++) { if (matrix[i][j] === 5) { break outerLoop; } console.log(matrix[i][j]); } } |
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.