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

วิธีเพิ่มโค้ด Debug (Debugging Code) ใน JavaScript

การเพิ่มโค้ด Debug ช่วยให้เห็นค่าตัวแปร ลำดับการทำงาน และสถานะของโปรแกรมขณะรัน ได้ 2 วิธีหลักคือ alert() และ document.write() แต่ในปัจจุบันแนะนำให้ใช้ Console API และ Debugger แทน

วิธีเก่า (Basic) - ใช้ในการสอน/ทดสอบด่วน

1. alert() - แสดงกล่องข้อความ

var debugging = true;
var whichImage = "widget";

if (debugging) alert("Calls swapImage() with argument: " + whichImage);

var swapStatus = swapImage(whichImage);

if (debugging) alert("Exits swapImage() with swapStatus=" + swapStatus);

ข้อเสีย: บล็อก UI, ไม่แสดง Object/Array ได้สวย, รบกวนการทำงาน

2. document.write() - เขียนลงหน้าเว็บ

if (debugging) document.write("Debug: whichImage = " + whichImage + "<br>");

ข้อเสีย: เขียนทับหน้าเว็บ, ไม่ทำงานหลังโหลดเสร็จ (after document close), ไม่เหมาะกับ Production

วิธีสมัยใหม่ (Modern) - แนะนำใช้จริง

1. Console API (Developer Tools Console - F12)

console.log("ค่าปกติ:", variable);
console.info("ข้อมูล:", data);
console.warn("คำเตือน:", deprecatedFunction);
console.error("ข้อผิดพลาด:", error);
console.debug("รายละเอียด Debug:", {user, config, timestamp}); // แสดงได้ตอนเปิด Verbose

// แสดงตาราง
console.table(arrayOfObjects);

// กลุ่มข้อความ
console.group("User Login Process");
console.log("Step 1: Validate input");
console.log("Step 2: Call API");
console.groupEnd();

// วัดเวลา
console.time("fetchData");
await fetchData();
console.timeEnd("fetchData");

// Stack Trace
console.trace("Function called from here");

2. debugger Statement (Breakpoint ในโค้ด)

function swapImage(whichImage) {
  debugger; // หยุดที่นี่เมื่อเปิด DevTools
  // โค้ด...
}
  • เปิด DevTools (F12) → รันโค้ด → จะหยุดที่บรรทัด debugger
  • สามารถ Inspect Variables, Call Stack, Step Over/Into/Out ได้

3. Conditional Breakpoints (ใน DevTools Sources Tab)

  • คลิกขวาที่ Line Number > Add conditional breakpoint
  • ใส่เงื่อนไข เช่น user.id === 123 หรือ retryCount > 3

4. Logpoints (Log โดยไม่หยุดโปรแกรม)

  • คลิกขวาที่ Line Number > Add logpoint
  • ใส่ข้อความ: User ${user.name} logged in with role ${user.role}

Best Practices สำหรับ Debugging

  1. ใช้ Source Maps สำหรับ Minified/Transpiled Code (Webpack, Vite, TypeScript)
  2. Wrap ใน Debug Flag: if (process.env.NODE_ENV === 'development') { console.debug(...) }
  3. Structured Logging: ใช้ Object แทน String Concatenation: console.log({event: 'login', userId, duration})
  4. ไม่ commit console.log/debugger ไป Production (ใช้ ESLint rule: no-console, no-debugger)
  5. ใช้ Logging Library สำหรับ Production: pino, winston, loglevel

สรุป

  • alert()/document.write(): ใช้ได้เฉพาะทดสอบเร็วๆ แบบ Ad-hoc
  • console.* + debugger + Breakpoints/Logpoints: มาตรฐานมืออาชีพ ให้ข้อมูลมากกว่า ไม่รบกวน UI
  • Production Logging: ใช้ Library ที่รองรับ Level, Rotation, Structured JSON