You would have probably used break
or continue
in your javascript code at least once. Break and continue in javascript are known as jump statements. Let's look into both the statements.
Break
The break
statement causes the innermost enclosing loop or switch statement to exit immediately.
You would be already familiar how break
works in switch
statements and it can be used to break a statement prematurely with or without any condition or reason. However in a for
loop break can be used to exit when it finds a match and no longer need to loop through next elements like below.
for(let item of array) {
if (item === target) break;
}
Break with labels
Break
can be used with a label, it jumps to the end of, or terminates, the enclosing statement that has the specified label.
Note: With this form of the break statement, the named statement need not be a loop or switch: break can break from any enclosing statement (except you cannot label a function definition statement and then use that label inside the function).
let matrix = getData(); // Get array of numbers
// Now sum all the numbers in the matrix.
let sum = 0, success = false;
// Start with a labeled statement that we can break out of if errors occur
computeSum: if (matrix) {
for(let x = 0; x < matrix.length; x++) {
let row = matrix[x];
if (!row) break computeSum;
for(let y = 0; y < row.length; y++) {
let cell = row[y];
if (isNaN(cell)) break computeSum;
sum += cell;
}
}
success = true;
}
Continue
The continue
statement continues restarting a loop at the next iteration, instead of exiting a loop.
for(let i = 0; i < array.length; i++) {
if (!array[i]) continue; // Can't proceed with undefined
total += array[i];
}
Continue with labels
Unlike break
, the continue
statement, in both its labeled and unlabeled statements, can be used only within the body of a loop.
const array = [[1, "one"], [2, "two"], [3, "three"], [4, "four"]];
outer: for (const arrayElement of array) {
inner: for (const arrayElementElement of arrayElement) {
if(typeof (arrayElementElement) === "number"){
console.log(`${arrayElementElement} is a number`);
continue outer;
}
console.log(arrayElement); //this would not be logged
}
}
Continue statement works differently for different types of loops:
while
loop
The specified expression at the beginning of the loop is tested again, and if itβs true, the loop body is executed starting from the top.
do/while
loop
Execution skips to the bottom of the loop, where the loop condition is tested again before restarting the loop at the top.
for
loop
The increment expression is evaluated, and the test expression is tested again to determine if another iteration should be done.
for/of
or for/in
loop
The loop starts over with the next iterated value or next property name being assigned to the specified variable.
Hope you will make use of break and continue with this understanding next time on you code. If you have any questions or comments please type in below.
References:
Top comments (0)