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.

example

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.

break-loop

Breaking a Switch Case

Exiting a switch case is equally simple. Place the Break block inside a Case block, like this.

break-switch

If the condition of Case A is true, then exit the switch without checking whether the condition of Case B is satisfied.

Breaking an Outer Loop

By default, the Break block exits the nearest loop it’s inside. However, in more complex scenarios, you can also break out of a specific outer loop, like this:

break-outer

This is useful when you want to stop all iterations early once a certain condition is met, instead of just exiting the inner loop.

If you’re familiar with JavaScript, this works the same way as using a labeled break, for example:

L725: for (const j of [1, 2, 3]) {
  L393: for (const k of ['a', 'b', 'c']) {
    if (j === 2) {
      break L725
    }
  }
}

Tip: Use outer breaks sparingly—while they can simplify certain workflows, overusing them may make your logic harder to follow.