Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

การใช้คำสั่ง goto ใน JavaScript


goto เป็น Reserved Keyword ใน JavaScript ไม่สามารถใช้งานได้โดยตรง มาตรฐานเว็บไม่แนะนำการใช้ goto เพราะทำให้โค้ดยากต่อการอ่านและบำรุงรักษา (Spaghetti Code)

ทางเลือก: Preprocessing / Transpilation

บาง Tool/Preprocessor รองรับ goto แล้วแปลงเป็นโค้ด JavaScript มาตรฐาน:

โค้ดต้นทาง (Pseudo-code with goto)

var a = 0;
[lbl] beginning:
console.log("Demo Text!");
a++;
if (a < 424) goto beginning;

โค้ดที่แปลงแล้ว (Transpiled)

var a = 0;
beginning: while (true) {
  console.log("Demo Text!");
  a++;
  if (a < 424) continue beginning;
  break;
}

วิธีการเขียนแทน goto ใน JavaScript มาตรฐาน

1. ใช้ Loop + Continue/Break (Structured Programming)

// แทน goto label
while (true) {
  // โค้ดที่ต้องทำซ้ำ
  if (condition) continue; // กลับไปต้นลูป
  if (done) break;         // ออกจากลูป
}

2. ใช้ Function + Return (Early Exit)

function process() {
  // โค้ดก่อน
  if (errorCondition) return; // แทน goto cleanup
  
  // โค้ดหลัก
  return result;
}

3. ใช้ State Machine Pattern

const states = {
  START: 'start',
  PROCESSING: 'processing',
  END: 'end'
};

let currentState = states.START;
while (currentState !== states.END) {
  switch (currentState) {
    case states.START:
      init();
      currentState = states.PROCESSING;
      break;
    case states.PROCESSING:
      if (done) currentState = states.END;
      break;
  }
}

4. ใช้ Exception สำหรับ Error Handling (Non-local Goto)

try {
  // Deep nested code
  if (criticalError) throw new CriticalError();
} catch (e) {
  if (e instanceof CriticalError) {
    // Cleanup - ทำหน้าที่เหมือน goto errorHandler
  }
}

ทำไมไม่ควรใช้ Goto

  • ทำให้ Control Flow ยากต่อการติดตาม (Unstructured)
  • เพิ่ม Cognitive Load ให้ Programmer
  • ทำให้ Testing และ Debugging ยาก
  • Modern Languages มี Control Structures ครบครัน (Loop, Function, Exception, Async/Await)
  • Dijkstra: "Goto Statement Considered Harmful" (1968)

สรุป

JavaScript ไม่มี goto ให้ใช้งาน ให้ใช้โครงสร้างควบคุมมาตรฐาน (if, for, while, function, try/catch, async/await) ซึ่งเพียงพอและปลอดภัยกว่ามาก