break
and continue
statements in JS
Exit for loops and iterations prematurely
Often times a loop is executed until a certain condition evaluates to true, exiting its workload prematurely. In JavaScript, the continue
statement is used to exit a foor loop iteration before it concludes, whereas the break
statement is used to exit a for loop entirely before it concludes. It's worth pointing out the break
and continue
statements are applicable to any JavaScript type of loop and not just loops created with the for
statement presented earlier.
Listing 6-2 illustrates the use of the break
and continue
statements in for loops.
Listing 6-2. For loops with break
and continue
statements
let primeNumbers = [2,3,5,7,11]; const primeLength = primeNumbers.length; for (let i = 0; i < primeLength; i++) { // Continue to next iteration when primeNumber > 4 & < 10 if (primeNumbers[i] > 4 && primeNumbers[i] < 10) { continue; } console.log(primeNumbers[i]); } let vowels = ["a","e","i","o","u"]; const vowelsLength = vowels.length; console.log("vowels ",vowelsLength); for (let j = vowelsLength-1; j >= 0; j--) { // Break loop when vowel == "i" if (vowels[j] == "i") { break; } console.log(vowels[j]); }
The first example in listing 6-2 loops over the primeNumbers
array and inside the block of code checks if the value of the iteration on primeNumbers
is larger than 4
or lower than 10
to invoke a continue
statement. In this case, when a primeNumbers
value is between 4
and 10
the continue
statement causes the loop to immediately move to the next iteration, skipping the log statement when the primeNumbers
iteration value is 5
and 7
.
The second example in listing 6-2 loops over the vowels
array with a decreasing counter to facilitate a reverse order loop. Inside the block of code, notice a check is made for when the value of the iteration on vowels
equals "i"
to invoke a break
statement. In this case, when a vowels
value equals "i"
, the condition evaluates to true and the break
statement causes the loop to finish immediately, skipping the log statement when the vowels
iteration value equals "i"
, as well as any remaining iterations (i.e. when a vowels
value is "e"
and "a"
).