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

JavaScript Validator คืออะไร

นิยาม

JavaScript Validator (หรือ Validating Parser) คือโปรแกรมที่ตรวจสอบโค้ด JavaScript ให้ถูกต้องตาม Syntax Rules ของภาษา ช่วยหา Bug แปลกๆ ที่หายาก

Validator ยอดนิยม: JSLint / ESLint

เครื่องมือที่แนะนำที่สุดคือ ESLint (ทดแทน JSLint ที่เก่า) โดย Douglas Crockford สร้าง JSLint ต้นกำเนิด

วิธีใช้ ESLint

  1. ติดตั้ง: npm install eslint --save-dev
  2. ตั้งค่า: npx eslint --init
  3. รันตรวจสอบ: npx eslint yourfile.js
  4. Auto-fix: npx eslint --fix yourfile.js

สิ่งที่ Validator ตรวจสอบ

  • Syntax Errors: Missing brackets, semicolons, reserved words
  • Variable/Function Declarations: Undeclared variables, unused variables
  • Statement Format: if, while, for, switch syntax
  • Best Practices: == vs ===, eval(), with statement
  • Style: Indentation, quotes, semicolons, line length
  • Potential Bugs: Null/Undefined access, infinite loops

ตัวอย่าง Error ที่ ESLint จับได้

// 1. Undefined variable
console.log(undefinedVariable); // 'undefinedVariable' is not defined

// 2. Unused variable
var x = 10; // 'x' is assigned a value but never used

// 3. == instead of ===
if (x == "10") {} // Expected '===' and instead saw '=='

// 4. Missing semicolon (ถ้ากำหนด require)
function foo() {
  return
  1; // Unexpected semicolon (ASI issue)
}

// 5. Block-scoped var (should use let/const)
for (var i = 0; i < 10; i++) {} // 'i' is defined but never used outside loop

Online Validators

  • ESLint Demo - ทดสอบออนไลน์
  • JSHint - เก่าแต่อยู่ได้
  • JSLint - ต้นกำเนิด เข้มงวดมาก

การตั้งค่าใน Editor (VS Code)

// .vscode/settings.json
{
  "eslint.enable": true,
  "eslint.validate": ["javascript", "javascriptreact", "typescript", "typescriptreact"],
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": "explicit"
  }
}

สรุป

JavaScript Validator (ESLint) ตรวจสอบ Syntax, Best Practices, Potential Bugs ใช้ผ่าน CLI, Editor Integration หรือ Online Demo ช่วยจับ Bug ก่อน Run จริง