break และ continue เป็นคำสั่งควบคุมการไหลในลูป (Loop Control Statements) ที่ทำงานต่างกันอย่างสิ้นเชิง:
| คำสั่ง | พฤติกรรม | ผลลัพธ์ |
|---|---|---|
break | ออกจากลูป ทันทีและสิ้นสุด ลูป | ไม่รันรอบที่เหลือเลย |
continue | ข้าม เฉพาะรอบปัจจุบัน ไปรอบถัดไป | ข้ามโค้ดที่เหลือในรอบนี้ รอบต่อไปทำงานปกติ |
break Statement
ใช้เมื่อต้องการ หยุดลูปทั้งหมด ทันทีเมื่อเจอเงื่อนไข
ตัวอย่าง
<html>
<body>
<script>
var x = 1;
document.write("Entering the loop<br />");
while (x < 20) {
if (x == 5) {
break; // ออกจากลูปทันที
}
x = x + 1;
document.write(x + "<br />");
}
document.write("Exiting the loop!<br />");
</script>
</body>
</html>
ผลลัพธ์
Entering the loop 2 3 4 5 Exiting the loop!
continue Statement
ใช้เมื่อต้องการ ข้ามเฉพาะรอบนี้ ไปรอบถัดไปทันที
ตัวอย่าง
<html>
<body>
<script>
var x = 1;
document.write("Entering the loop<br />");
while (x < 10) {
x = x + 1;
if (x == 8) {
continue; // ข้ามการพิมพ์ 8 ไปรอบ 9 ทันที
}
document.write(x + "<br />");
}
document.write("Exiting the loop!<br />");
</script>
</body>
</html>
ผลลัพธ์
Entering the loop 2 3 4 5 6 7 9 10 Exiting the loop!
สังเกต: เลข 8 หายไป (ถูก continue ข้าม) แต่ลูปยังทำงานต่อจนครบ 10
การใช้งานร่วมกับ Nested Loops (ลูปซ้อน)
ทั้ง break และ continue ทำงานกับ ลูปชั้นในสุด (Innermost) เท่านั้น หากต้องการควบคุมลูปชั้นนอก ใช้ Label Statement
outer: for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
if (j === 1) break outer; // ออกจาก outer loop
if (j === 2) continue outer; // ข้ามรอบ outer ที่เหลือ ไปรอบ i ถัดไป
console.log(i, j);
}
}
สรุปการเลือกใช้
- ใช้ break เมื่อ: พบสิ่งที่ต้องการแล้ว / เกิด Error / ต้องการหยุดประมวลผล
- ใช้ continue เมื่อ: ข้ามข้อมูลที่ไม่ต้องการ / Skip Validation Failed / Filter ในลูป
ตัวอย่างในทางปฏิบัติ
// break: หยุดค้นหาเมื่อเจอ
function findUser(users, targetId) {
for (const user of users) {
if (user.id === targetId) return user; // Early return = break แบบมีค่า
}
return null;
}
// continue: กรองข้อมูล
function processValidItems(items) {
for (const item of items) {
if (!item.isValid) continue; // ข้าม invalid
if (item.isProcessed) continue; // ข้ามที่ทำไปแล้ว
processItem(item);
}
}