Loop Control in JavaScript: break and continue
Loops are powerful, but sometimes they just need to chill. Enter break
and continue
, the ultimate loop managers. break
stops the loop entirely, like rage-quitting a game. continue
skips the current iteration and moves to the next one, like pretending you didn’t see that embarrassing typo.
1. break
: The Escape Artist
When you use break
, your loop just stops—no questions asked. It’s like realizing you’re in the wrong Zoom meeting and exiting immediately.
Example:
for (let i = 1; i <= 5; i++) {
if (i === 3) {
console.log("Breaking at 3! I'm out!");
break;
}
console.log("Iteration " + i);
}
Output:
Iteration 1
Iteration 2
Breaking at 3! I'm out!
Real-life analogy: You walk into a party, see your ex, and leave immediately.
2. continue
: The Selective Ignorer
The continue
statement skips the current loop iteration and moves to the next one. It’s like scrolling past a spoiler without reading it.
Example:
for (let i = 1; i <= 5; i++) {
if (i === 3) {
console.log("Skipping 3! Not today!");
continue;
}
console.log("Iteration " + i);
}
Output:
Iteration 1
Iteration 2
Skipping 3! Not today!
Iteration 4
Iteration 5
Real-life analogy: When you see veggies on your plate and just eat the fries.
3. break
vs continue
: Spot the Difference
Feature | break |
continue |
---|---|---|
Stops the loop completely? | Yes | No |
Skips just one iteration? | No | Yes |
Common analogy | Rage quitting a game 🎮 | Skipping a bad song on shuffle |
4. break
and continue
in while
Loops
These work the same way in while
loops too!
Example:
let num = 0;
while (num < 5) {
num++;
if (num === 3) {
console.log("Skipping 3 in while loop!");
continue;
}
console.log("Number: " + num);
}
5. Be Careful!
Overusing break
and continue
can make your code harder to read. Use them wisely—like a ninja, not a berserker.
Conclusion
break
and continue
help control loops efficiently. break
is your emergency exit, while continue
is your selective skip button. Use them smartly to make your code cleaner and funnier!
Comments
Post a Comment