4.9 Break and Continue
With all the loops you have discovered in this section, there are two key words, which can change the behavior of the break and continue loop. In this demonstration, I will use a while loop. But what you are about to learn applies to all the loops we have learned in this section. So let's start by declaring a variable called i and initializing it to 0. Now we put that in a while loop, as long as while is less than or equal to 10, we'll display i on the console, and then increment it. We save the changes and so that gives us the numbers from 0 to 10. Now, sometimes you want to get out of a loop for a reason that may occur at runtime. For example, here we can have an if condition and an if statement, with a condition like this. If i is equal to 5, we want to exit this loop. This is where we use the break keyword. when we save the changes, we get the numbers from 0 to 4. So at the end of the 5th iteration, we increment i, now at 5, we get out of the loop. we'll comment on that next and look at the continue keyword. So I'll write another if statement, I want to see if i is an even number or not. So we make i, modulo 2, equal to 0. If it is, I want to increment i and then continue. Let's see what happens when we run this code. Save the changes, we only get the odd numbers So why? Let's look at an example. So, when i is 2, it is an even number and when we increment i i will be equal 3. Now when the JavaScript engine sees the keyword continue. It will jump to the beginning of the loop. And continue its execution in the next iteration. At this point, i is equal to 3, so this if statement is not executed, that's why we see i on the console. On the other hand the continue keyword is not something you will use often, it's one of those old legacy things in JavaScript. It's not something that I recommend you use. So that's it for this little demonstration on the break and continue keywords, so to recap with the break keyword, you jump out of a loop, and with the continue keyword, we go to the next iteration.