Developer ต้อง Debug บ่อย console.log เป็นวิธีง่ายสุด แต่ Browser DevTools มีเทคนิคเยี่ยมกว่านี้มาก
ลับของ freeCodeCamp Code Editor
ใช้ CodeMirror ที่ปรับแต่งเอง eval() รัน JavaScript จาก Editor เป็น String Browser Execute โค้ด Native — จุดสำคัญสำหรับ Debugging ต่อไป
เทคนิค Debugging ใน Chrome DevTools
1. พื้นฐาน DevTools
เปิด DevTools
F12Ctrl+Shift+I(Win/Linux) /Cmd+Shift+I(Mac)- Menu > More Tools > Developer Tools
Tabs สำคัญ: Sources และ Console
- Sources: ดู Script ทั้งหมดบนเพจ มี Code Window, File Tree, Call Stack, Watch
- Console: Log Output + REPL รัน JS ได้ (เหมือน Terminal)
Tip: กด Esc Toggle Console ได้ตลอด
2. Shortcuts และ Features พื้นฐาน
| Feature | Windows/Linux | Mac |
|---|---|---|
| Search (Regex OK) | Ctrl+F | Cmd+F |
| Search & Open File | Ctrl+P | Cmd+P |
| Jump to Line | Ctrl+G + :line_no | Cmd+G + :line_no |
| Add Breakpoint | Ctrl+B หรือคลิก Line Number | Cmd+B หรือคลิก Line Number |
| Pause/Resume | F8 | F8 |
| Step Over | F10 | F10 |
| Step Into | F11 | F11 |
3. ใช้ Source Map สำหรับ Dynamic Script (เช่น eval)
โค้ดจาก Editor รันผ่าน eval() ใน VM (Virtual Machine) ไม่มีชื่อไฟล์ -> ไม่見在 Sources Tab
วิธีแก้: ใช้ //# sourceURL
เพิ่มบรรทัดแรกของโค้ด:
//# sourceURL=factorialize.js
function factorialize(num) {
if(num <= 1){ ... }
}
factorialize(5);
ตอนนี้ DevTools จะเห็นไฟล์ factorialize.js ใน Sources Tab -> วาง Breakpoint, Debug ได้เลย!
แหล่งอ่านเพิ่มเติม
- Beginner's guide to bug squashing
- Debugging tips and tricks for beginners
- How to get the most out of your browser's debugging console