27
loading...
This website collects cookies to deliver better user experience
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
statement causes the innermost enclosing loop or switch statement to exit immediately.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
can be used with a label, it jumps to the end of, or terminates, the enclosing statement that has the specified label. 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
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];
}
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
}
}