JavaScript Identifiers คือ ชื่อสำหรับ Variables, Functions, Classes, Properties ฯลฯ ต้องปฏิบัติตามกฎดังนี้:
กฎข้อห้าม (Must Not)
- ห้ามใช้ Reserved Keywords:
break, case, catch, class, const, continue, debugger, default, delete, do, else, export, extends, false, finally, for, function, if, import, in, instanceof, new, null, return, super, switch, this, throw, true, try, typeof, var, void, while, with, yieldและ Future Reserved Words:enum, implements, interface, package, private, protected, public, static - ห้ามขึ้นต้นด้วยตัวเลข (0-9):
5demo❌ →_5demo✅ หรือdemo5✅
กฎที่อนุญาต (Allowed)
- ตัวอักษร (a-z, A-Z, Unicode Letters)
- ตัวเลข (0-9) ไม่ใช่ตัวแรก
- Underscore (
_) - Dollar Sign (
$)
Case Sensitivity
JavaScript Case-Sensitive: Name ≠ name ≠ NAME
ตัวอย่าง Valid/Invalid
| Identifier | Valid? | เหตุผล |
|---|---|---|
userName | ✅ | CamelCase ปกติ |
_private | ✅ | ขึ้นต้น _ ได้ |
$element | ✅ | ขึ้นต้น $ ได้ |
var | ❌ | Reserved Keyword |
123abc | ❌ | ขึ้นต้นตัวเลข |
my-var | ❌ | Hyphen ไม่ได้ (ใช้ myVar) |
ชื่อตัวแปร | ✅ | Unicode OK แต่ไม่แนะนำ |
Naming Conventions (แนวทางมาตรฐาน)
| ประเภท | Style | ตัวอย่าง |
|---|---|---|
| Variables/Functions | camelCase | userName, getUserData |
| Constants | UPPER_SNAKE_CASE | MAX_SIZE, API_ENDPOINT |
| Classes/Constructors | PascalCase | User, HttpClient |
| Private (Convention) | _prefix | _internalHelper |
| Boolean | is/has/can/should | isActive, hasAccess |