Online Compiler logoOnline Compiler

JavaScript Tutorial

JavaScript break Statement

The break statement stops a loop or switch immediately.

It is useful for early exits when a condition is met.

Why We Need It

Without break, loops always run to completion even when the result is already known.

Using break correctly saves time and improves clarity.

Syntax

break;

Basic Example

1. Break in a loop

for (let i = 0; i < 5; i++) {
  if (i === 3) break;
  console.log(i);
}

Stops the loop once i reaches 3.

Real World Example

2. Break in search

const items = [5, 7, 9, 12];
let found = false;

for (const item of items) {
  if (item === 9) {
    found = true;
    break;
  }
}

...

Exit as soon as the item is found.

Multiple Use Cases

Exit Early

The break statement stops a loop or switch immediately.

Use it when you have found what you need and want to exit early.

Search Patterns

break is common in search loops to stop after a match is found.

It prevents unnecessary work and keeps code efficient.

Switch Cases

In switch statements, break prevents fall-through to the next case.

Most cases should end with break.

More Examples

3. Break in switch

const role = "admin";

switch (role) {
  case "admin":
    console.log("All access");
    break;
  default:
    console.log("Read access");
}

Prevents fall-through in switch statements.

4. Nested loops

let foundPair = false;
for (let i = 0; i < 3 && !foundPair; i++) {
  for (let j = 0; j < 3; j++) {
    if (i + j === 4) {
      foundPair = true;
      break;
    }
  }
}
console.log(foundPair);

Break only exits the inner loop. Use flags for outer loops.

Comparison

Without

for (let i = 0; i < 5; i++) {
  if (i === 3) {
    i = 5;
  }
}

With

for (let i = 0; i < 5; i++) {
  if (i === 3) break;
}

Common Mistakes and Fixes

Breaking the wrong loop

Remember break only exits the nearest loop or switch.

Using break instead of return

If you want to exit a function, return is clearer.

Missing break in switch

Add break to avoid accidental fall-through.

Interview Questions

What does break do?

It exits the nearest loop or switch immediately.

How do you break out of nested loops?

Use a flag or a labeled break.

When should you use break?

When you have already found the result and want to stop looping.

Practice Problem

Practice: Stop a loop once you find the first even number in an array.

const nums = [1, 3, 5, 8, 10];
// TODO: find first even and stop

One Possible Solution

const nums = [1, 3, 5, 8, 10];
let firstEven;
for (const n of nums) {
  if (n % 2 === 0) {
    firstEven = n;
    break;
  }
}
console.log(firstEven);

Frequently Asked Questions

Does break work outside loops?

No, it only works inside loops and switch statements.

How do I break an outer loop?

Use a flag or labeled break (rarely used).

Is break the same as return?

No, return exits the function; break exits the loop or switch.

Try It Yourself

Try changing the break condition to see when the loop stops.