Example 1 — break in while
Stop when a condition appears mid-body.
JavaScript
let i = 0;
while (true) {
if (i === 2) break;
console.log(i);
i++;
} How It Works
- Infinite while until break.
- Stops when i is 2.
break leaves the nearest loop or switch. continue skips the rest of the current loop iteration and goes to the next one.
for (let i = 0; i < 5; i++) {
if (i === 1) continue;
if (i === 3) break;
console.log(i);
} Stop when a condition appears mid-body.
let i = 0;
while (true) {
if (i === 2) break;
console.log(i);
i++;
} Jump to the next iteration.
for (const n of [1, 2, 3, 4]) {
if (n % 2 === 0) continue;
console.log(n);
} Prevents fall-through.
switch (1) {
case 1: console.log("one"); break;
case 2: console.log("two"); break;
} CODETOFUN NEWS
Get the latest IT news, programming updates, and technology trends directly on your phone.
Your daily dose of tech, straight to your feed.
6 people found this page helpful