JavaScript Identifiers คือ ชื่อที่ใช้ระบุ Variables, Functions, Parameters, Classes, Properties, Labels เหมือนภาษาอื่น (C, C++, Java)
ตัวอย่าง Identifier ที่ถูกต้อง
val val1 result userName $price _element myFunction PI
กฎการตั้งชื่อ (Naming Rules)
- ห้ามใช้ 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และคำสงวนอนาคต (enum, implements, interface, package, private, protected, public, static) - ตัวแรกต้องเป็น: ตัวอักษร (a-z, A-Z), Underscore (
_), Dollar Sign ($) — ห้ามขึ้นต้นด้วยตัวเลข (0-9) - ตัวต่อไปเป็นได้: ตัวอักษร, ตัวเลข, Underscore, Dollar Sign
- Case-Sensitive:
nameและNameเป็นคนละตัวแปร - Unicode: รองรับ Unicode Letter (ภาษาไทย, จีน, ฯลฯ) ได้ แต่ไม่แนะนำสำหรับโค้ดร่วมงาน
ตัวอย่าง Invalid Identifiers
5demo // เริ่มต้นด้วยตัวเลข my-var // มี Hyphen (-) - ใช้ camelCase แทน: myVar function // Reserved Keyword class // Reserved Keyword const // Reserved Keyword
Valid แต่ควรหลีกเลี่ยง
_private // Convention: Private (แต่ JS ไม่ enforce) $element // Convention: jQuery/DOM Element __proto__ // Magic Property (หลีกเลี่ยง) constructor // Property Name ปกติ แต่สับสนกับ Class
Naming Conventions (แนวทางปฏิบัติ)
| ประเภท | Convention | ตัวอย่าง |
|---|---|---|
| Variables/Functions | camelCase | userName, getUserData |
| Constants | UPPER_SNAKE_CASE | MAX_SIZE, API_URL |
| Classes/Constructors | PascalCase | User, HttpClient |
| Private (Convention) | _prefix | _internalMethod |
| Boolean | is/has/can/should prefix | isActive, hasPermission |