JS Fundamentals #20 break, continue and switch in JavaScript
Control flow is at the heart of programming — and JavaScript offers several statements that give you fine-grained control over loops and conditionals. In this article, we’ll explore the break, continue, and switch statements as well as default and case keywords with examples to help you understand when and how to use them.
🚪 break Statement
The break statement exits a loop or a switch block early, stopping further execution.
📌 Use Case:
Exiting a
for,while, ordo...whileloop when a certain condition is met.Exiting from a
switchcase once the matching condition is handled.
✅ Example: Exiting a Loop
for (let i = 1; i <= 5; i++) {
if (i === 3) break;
console.log(i); // prints 1 and 2
}
✅ Example: In a switch
let fruit = 'apple';
switch (fruit) {
case 'apple':
console.log('It’s an apple');
break; // exits the switch
case 'banana':
console.log('It’s a banana');
break;
default:
console.log('Unknown fruit');
}
🔄 continue Statement
The continue statement skips the current iteration of the loop and jumps to the next one.
📌 Use Case:
- You want to skip processing for some specific cases but keep the loop running.
✅ Example:
for (let i = 1; i <= 5; i++) {
if (i === 3) continue;
console.log(i); // prints 1, 2, 4, 5 (skips 3)
}
🧠 switch Statement
The switch statement provides an elegant alternative to multiple if...else if...else blocks, especially when checking against discrete values.
📌 Use Case:
- Use when comparing one value against many possible constant matches.
✅ Basic Structure:
switch (expression) {
case value1:
// code block
break;
case value2:
// code block
break;
default:
// default block
}
🧩 default keyword in switch
The default keyword provides a fallback case in a switch block — similar to else in an if-else ladder.
✅ Example:
let day = 'Wednesday';
switch (day) {
case 'Monday':
console.log('Start your week strong!');
break;
case 'Friday':
console.log('Almost the weekend!');
break;
case 'Sunday':
console.log('Rest and recharge!');
break;
default:
console.log('Just another regular day.');
}
If no case matches, the default block executes.
🔁 Summary Table
| Keyword | What It Does | Typical Usage Area |
break | Exits a loop or switch early | for, while, switch |
continue | Skips current loop iteration | for, while loops |
switch | Compares one value to multiple cases | Replacing if-else ladders |
default | Fallback block in a switch statement | switch only |
🎯 Final Thoughts
Understanding break, continue, switch, and default helps you write cleaner, more readable, and efficient control flow in JavaScript. These small but powerful keywords often make a big difference in how your logic behaves — especially in loops and multi-branch decision structures.