A break
statement is used to exit a loop early, while a continue
statement is used to skip the current iteration of a loop and move to the next one.
Here is an example of using a break
statement in a for
loop:
for (let i = 0; i < 10; i++) {
if (i === 5) {
break;
}
console.log(i);
}
In the example above, the loop starts counting at 0
and while i
is less then 10
, the loop will continue to run.
Inside the loop, we check if i
is equal to 5
. If it is, we use the break
statement to exit the loop early. If not, we log the value of i
to the console. So the output of the code will print the numbers 0
, 1
, 2
, 3
, and 4
.
The break
statement is useful when you want to exit a loop early based on a certain condition. For example, if you are searching for a specific value in an array, you can use a break
statement to exit the loop once you find the value.
Sometimes you may want to skip a particular iteration of a loop without exiting the loop entirely. This is where the continue
statement comes in. Here is an example of using a continue
statement in a for
loop:
for (let i = 0; i < 10; i++) {
if (i === 5) {
continue;
}
console.log(i);
}
Just like before, we have initialized i
to 0
and have a condition that will run the loop as long as i
is less than 10
.
Inside the loop, when i
is equal to 5
, we use the continue
statement to skip the current iteration and move to the next one.
The output of this code will print the numbers 0
, 1
, 2
, 3
, 4
, 6
, 7
, 8
, and 9
. The number 5
is skipped because of the continue
statement.
Another thing you can do with both the break
and continue
statements is to use labels to specify which loop you want to break or continue.
This is useful when you have nested loops and you want to control the flow of the outer loop from within the inner loop.
Here is an example of using labels with the break
statement:
outerLoop: for (let i = 0; i < 3; i++) {
innerLoop: for (let j = 0; j < 3; j++) {
if (i === 1 && j === 1) {
break outerLoop;
}
console.log(`i: ${i}, j: ${j}`);
}
}
In this example, we have an outer for
loop labeled outerLoop
and an inner for
loop labeled innerLoop
.
When i
is equal to 1
and j
is equal to 1
, we use the break
statement with the outerLoop
label to exit the outer loop early. This will exit both the inner and outer loops.
The output of this code will log the following to the console:
"i: 0, j: 0"
"i: 0, j: 1"
"i: 0, j: 2"
"i: 1, j: 0"
Most of the time you will not find the need to use labels with the break
and continue
statements, but it is good to know that you have that option if you ever need it.