Break
In this section, we will guide you on how to use the Break block.
Use Cases
The break statement in JavaScript is a control flow statement used to exit loops or switch statements. It is often used with if conditions to terminate the current loop or case execution prematurely. Below are some common use cases for the break statement:
1. Exiting a Loop Early
This example exits the loop immediately when the value b
is found, skipping the rest of the items.
const items = ['a', 'b', 'c']
for (let [index, value] of Object.entries(items)) {
if (value === 'b') {
break
}
console.log(index, value)
}
2. Exiting a Switch Case Early
If day
is Sunday
, the break statement is executed after the first matching case, skipping any further checks.
const day = 'Sunday'
switch (day) {
case 'Saturday':
case 'Sunday':
console.log('Weekend!')
break
case 'Monday':
console.log('Meeting')
break
default:
console.log('Weekday')
}
3. Exiting Nested Loops
When outerValue = "a"
and innerValue = "b"
, the inner loop is exited early.
const items = ['a', 'b', 'c']
for (let [outerIndex, outerValue] of Object.entries(items)) {
for (let [innerIndex, innerValue] of Object.entries(items)) {
if (outerValue === 'a' && innerValue === 'b') {
break
}
console.log(outerValue, innerValue)
}
}
In Tapicker, the behavior of the Break block is identical to JavaScript's break statement.
Breaking a Loop
If you want to exit a loop, here's a simple example. It shows that when the loop value equals b
, the loop L608
is terminated.
Breaking a Switch Case
Exiting a switch case is equally simple. Place the Break block inside a Case block, like this.
If the condition of Case A is true, then exit the switch without checking whether the condition of Case B is satisfied.