Break and Continue
The break and continue statements are used mainly with loops and their purpose is either to interrupt the loop or just jump the current iteration.
Break
The break statement interrupts the loop execution or a switch statement:
var x = 0;
while (x < 10) {
console.log(x);
x++;
if (x == 5) {
break;
}
}
In the above example we interrupted the loop before its condition (x < 10) returned false. Neste exemplo, conseguimos interromper o loop antes de atingir a condição (x < 10). This is just a simple example, but in some cases it could be very useful to interrupt a loop when something specific happens.
Continue
The continue statement is used to jump the current iteration of a loop.
Let's create a loop that will print only the even numbers from 0 to 20. First let's learn about the modulus operator (%).
This operator return the remainder of a division, so for instance if we do 6 % 4 the result is 2, which is the remainder of this division.
This means that we can use this operator to find out if a number is odd or even. The division of any even number by 2 produces no remainder while the division of any odd number by 2 always produce a remainder of 1. Therefore:
var num = 0;
num++;
while (num < 20) {
if (num % 2 != 0) {
continue;
}
console.log(num);
}