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.
JavaScript Tutorial
The break statement stops a loop or switch immediately.
It is useful for early exits when a condition is met.
Without break, loops always run to completion even when the result is already known.
Using break correctly saves time and improves clarity.
break;for (let i = 0; i < 5; i++) {
if (i === 3) break;
console.log(i);
}Stops the loop once i reaches 3.
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.
The break statement stops a loop or switch immediately.
Use it when you have found what you need and want to exit early.
break is common in search loops to stop after a match is found.
It prevents unnecessary work and keeps code efficient.
In switch statements, break prevents fall-through to the next case.
Most cases should end with break.
const role = "admin";
switch (role) {
case "admin":
console.log("All access");
break;
default:
console.log("Read access");
}Prevents fall-through in switch statements.
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.
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;
}Remember break only exits the nearest loop or switch.
If you want to exit a function, return is clearer.
Add break to avoid accidental fall-through.
It exits the nearest loop or switch immediately.
Use a flag or a labeled break.
When you have already found the result and want to stop looping.
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);No, it only works inside loops and switch statements.
Use a flag or labeled break (rarely used).
No, return exits the function; break exits the loop or switch.
Try changing the break condition to see when the loop stops.