How To Use: JavaScript Break and Continue Statements
Having worked with JavaScript for a long while now, there are times when you will find the need to break out of a loop when a certain condition is met, or just skip the current iteration to the next iteration for one reason or another. These situations can be solved by using the following statements:
- break statement
- continue statement
These statements can really come in handy to certain logic in the code or especially when wanting to avoid the long way of breaking a loop or skipping an iteration. Let’s see how they can be used.
Break Statement
The break
statement is used to terminate a loop and get out of
it. Then, the code following the loop code block will be executed next (if any). It is usually used inside
a conditional statement whereby when a condition is met, for one reason or another, it stops the loop and
gets out of it. How it is done is by simply writing break
.
Syntax:
break;
Example:
for (let i = 0; i < 8; i++) {
if (i === 4) { break; }
console.log("Iteration i: " + i);
}
// Output:
Iteration i: 0
Iteration i: 1
Iteration i: 2
Iteration i: 3
Without the break
statement, the output will typically appears as follow:
// Output:
Iteration i: 0
Iteration i: 1
Iteration i: 2
Iteration i: 3
Iteration i: 4
Iteration i: 5
Iteration i: 6
Iteration i: 7
So, to recap, based on the example above we
can see that when condition is met, the break
statement
is run and as the result, it terminates the loop immediately.
This statement also can be used in the switch
statements which are like conditional statements.
However, for this article, we will only take a look at the use for loops.
Continue Statement
The continue
statement is used to skip an iteration of the loop.
This statement too, can be used in the switch
statements.
The continue
statement basically breaks one iteration of the
loop, if a specified condition is met, and continues with the next iteration of the loop. How it is
written is similar to the break
statement.
Syntax:
continue;
Example:
for (let i = 0; i < 8; i++) {
if (i === 4) { continue; }
console.log("Iteration i: " + i);
}
// Output:
Iteration i: 0
Iteration i: 1
Iteration i: 2
Iteration i: 3
Iteration i: 5
Iteration i: 6
Iteration i: 7
Using the example above, we can see that the iteration 4 is skipped because we wrote that when it is 4, we will continue to the next iteration. Thus, its turn is skipped from being printed out.
Conclusion
That’s all for the two statements for now. They are just useful basics that might be used often in your code.
I hope this article is of help to you. If you think that this article is helpful and it can be of help to other people, please share for them to read as well. Your thoughts and comments are also welcome!
Thanks for reading~
Comments
Post a Comment