ใช้ Comments เพื่อ ปิดการทำงานของโค้ชั่วคราว (Comment Out) เพื่อทดสอบโค้ดใหม่ แล้วค่อย Uncomment กลับมา วิธีง่ายกว่าการลบโค้ดทิ้ง
กฎ Comments ใน JavaScript
| ประเภท | ไวยากรณ์ | ขอบเขต |
|---|---|---|
| Single-line | // comment | จนจบบรรทัด |
| Multi-line | /* comment */ | หลายบรรทัด |
| HTML-style Open | <!-- | Single-line (JS treat as //) |
| HTML-style Close | --> | ไม่ถูกจดจำ (ต้องเขียน //-->) |
ตัวอย่างการใช้งาน
<script> <!-- // This is a comment. คล้าย C++ /* * This is a multi-line comment in JavaScript * คล้าย C Programming */ //--> </script>
การ Comment Out โค้ดเพื่อทดสอบ
// โค้ดเดิม - Comment ไว้ก่อน
// function oldVersion() { ... }
// โค้ดใหม่ทดสอบ
function newVersion() {
console.log("New logic");
}
// ทดสอบเสร็จ → Uncomment โค้ดเดิม, ลบ/Comment โค้ดใหม่
Best Practices
- ใช้
//สำหรับบรรทัดเดียวหรือ Inline Comment - ใช้
/* */สำหรับบล็อกโค้ดหรือ Documentation (JSDoc) - อย่า Comment โค้ดไว้นานเกินไป → ลบทิ้ง (Git History มีอยู่แล้ว)
- JSDoc สำหรับ Document API:
/** @param {string} name */ - TODO/FIXME Tags:
// TODO: Refactor this,// FIXME: Bug here
IDE Shortcuts
- VS Code: Ctrl+/ (Toggle Line Comment), Shift+Alt+A (Block Comment)
- WebStorm/IntelliJ: Ctrl+/, Ctrl+Shift+/