When you work with loops, there are times when you need to interrupt the execution of code inside the code itself, without waiting for the next iteration. There are two keywords you can use to do this: break
and continue
.
The break
keyword stops execution of a for
or while
loop completely. The continue
keyword, on the other hand, stops execution of the code inside the loop and continues with the next iteration. Consider the following examples.
This example shows using break
if the day is Wednesday:
var days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"];
for (var idx in days){
if (days[idx] == "Wednesday")
break;
console.log("It's " + days[idx] + "<br>");
}
When the value is Wednesday
, loop execution stops completely:
It's Monday
It's Tuesday
This example shows using continue
if the day is Wednesday:
var days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"];
for (var idx in days){
if (days[idx] == "Wednesday")
continue;
console.log("It's " + days[idx] + "<br>");
}
Notice that the write is not executed for Wednesday
because of the continue
statement, but the loop execution does complete:
It's Monday
It's Tuesday
It's Thursday
It's Friday