Label Statement ใช้ ตั้งชื่อ (Identifier) ให้กับ Statement หรือ Block เพื่อให้ break และ continue สามารถ อ้างอิงเป้าหมายได้ชัดเจน โดยเฉพาะใน Nested Loops
ไวยากรณ์
labelName: statement
// หรือ
labelName: { statements }
ตัวอย่าง 1: Label กับ Break
<html>
<body>
<script>
document.write("Entering the loop!<br />");
outerloop:
for (var i = 0; i < 5; i++) {
document.write("Outerloop: " + i + "<br />");
innerloop:
for (var j = 0; j < 5; j++) {
if (j > 3) break;
if (i == 2) break innerloop;
if (i == 4) break outerloop;
document.write("Innerloop: " + j + " <br />");
}
}
document.write("Exiting the loop!<br />");
</script>
</body>
</html>
ตัวอย่าง 2: Label กับ Continue
<html>
<body>
<script>
document.write("Entering the loop!<br />");
outerloop:
for (var i = 0; i < 3; i++) {
document.write("Outerloop: " + i + "<br />");
for (var j = 0; j < 5; j++) {
if (j == 3) continue outerloop;
document.write("Innerloop: " + j + "<br />");
}
}
document.write("Exiting the loop!<br />");
</script>
</body>
</html>
Label กับ Block (ไม่ใช่ Loop)
Label สามารถใช้กับ Block { } ได้ แต่ break เท่านั้น (continue ไม่ได้):
myBlock: {
console.log("Start");
if (condition) break myBlock; // ออกจาก Block
console.log("Middle");
console.log("End");
}
console.log("After Block");
ข้อกำหนด Label Name
- ต้องเป็น Valid Identifier (ขึ้นต้นตัวอักษร, $, _ ตามด้วยตัวอักษร/ตัวเลข/$/_)
- ไม่ใช่ Reserved Word
- Case-sensitive
- Unique ใน Function Scope เดียวกัน
Scope และข้อจำกัด
- Label Scope = Function Scope (เหมือน
var) - ไม่สามารถ Jump ข้าม Function Boundary (ไม่ใช่ Goto)
break labelใช้ได้กับ Loop และ Blockcontinue labelใช้ได้กับ Loop เท่านั้น
แนวทางปฏิบัติและตัวเลือกแทน
| สถานการณ์ | แนะนำ |
|---|---|
| Break Nested Loop | Extract เป็น Function + Return |
| Continue Outer Loop | Guard Clause / Extract Function |
| Complex State Machine | State Pattern / Switch ใน While Loop |
| Legacy Code Maintenance | Label OK (ถ้า Refactor ยาก) |