The break and continue Keywords
With all the loops you have learned about, there are two keywords, break and continue, that can change how the loop behaves.
In this demo, I'm going to use a while loop, but what you're going to learn applies to all loops we have learned in this section.
Basic Loop Setup
-
Let's start by declaring a variable called
iand initializing it to 0. -
Now, we put this in a
whileloop. As long asiis less than or equal to 10, we're going to displayion the console and then increment it.let i = 0; while (i <= 10) { console.log(i); i++; } -
Save the changes. This gives us the numbers 0-10.

Output:
0 1 2 3 4 5 6 7 8 9 10
Using the break Keyword
Now, sometimes you want to jump out of a loop for some reason that may happen at runtime.
-
For example, here we can have an
ifstatement with a condition. Let's say ifiequals 5, we want to jump out of this loop. That's where we use thebreakkeyword.let i = 0; while (i <= 10) { if (i===5) break; console.log(i); i++; } -
We will modify the loop to add the
ifstatement inside the loop, after the increment, so it stops after printing4. -
Now when we save the changes, see what happens. We get the numbers 0 to 4.

Output:
0 1 2 3 4
Using the continue Keyword
Now, let me comment this out and look at the continue keyword.
let i = 0;
while (i <= 10) {
// if (i===5) break;
if (i%2===0){
i++;
continue;
}
console.log(i);
i++;
}
-
I'm going to write another
ifstatement. I want to see ifiis an even number or not. So,imodulus 2 equals 0. -
If that's the case (if
iis even), I want to incrementiand thencontinue. Thecontinuekeyword will jump to the beginning of the loop, skipping the code that comes after it. -
To get this to work and only log the odd numbers, the code needs to handle incrementing in two places:
-
once for the even numbers before continuing, and
-
once for the odd numbers after logging.
-
-
Save the changes. We only get the odd numbers.

Output:
1 3 5 7 9 -
Why is that? Alright, let's take a look at an example.
-
When
ibecomes 2, it's an even number. -
At this point, we increment
i, soiwill be 3. -
Now when the JavaScript engine sees the
continuekeyword, it will jump to the beginning of the loop and continue its execution in the next iteration. -
At this point
iis 3, so thisifstatement is not executed. That's why we seei(which is 3) on the console.
-
Note on continue :
In my personal experience, continue is not something you will use that often. It's one of those old, legacy things in JavaScript. I'm only explaining it here in case you see it in projects you're working on. It's not something that I recommend you to use; it's an ugly way of writing code.
Key Takeaway Just to recap:
-
With the
breakkeyword, you jump out of a loop. -
With the
continuekeyword, we jump to the next iteration.