We've briefly touched on the function of the break;
operator previously with the switch
statement, so let's quickly review how it works and how it affects loops. Just like the switch
statement, loops can be exited using the break;
statement. Note that if
, else-if
, and else
statements are not affected by the break;
statement. The break;
statement will exit the whole loop when it is called, disregarding the loop expression or the statements that come after it.
The break;
statement is used inside the while
loop to stop the entire loop if the value of counter
is equal to 5. This is why the while
loop stops printing the digits after 5 is printed on the console. As mentioned above, the if
statement is not affected by the break;
statement, which is why the entire loop is exited instead of the if
statement. The break;
statement can also be used with any of the other loops you will be learning later in the course and could potentially benefit you in the future by reducing the run-time of your code. For example, if you want to use a while
loop to find a certain value, you would want to exit the loop once it is found instead of executing all the possible cases.
Edit Me on GitHub!