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

JavaScript Variable Naming Conventions (Rules)

ต่อไปคือ กฎ (ไม่ใช่แนวทาง) สำหรับตั้งชื่อ JavaScript variable:

  • Variable names ประกอบได้แค่ alpha-numeric (a-z, 0-9), underscores (_) หรือ dollar sign $
  • Variable names ห้าม เริ่มต้นด้วยตัวเลข
  • Variable names ต้อง เริ่มต้นด้วย ตัวอักษร, dollar sign ($) หรือ underscore (_)
  • Variable names ห้าม มีช่องว่าง
  • Variable names ห้าม มี reserved keywords เช่น Javascript, true, this และอีกมากมาย

Reserved JavaScript Keywords

ถ้าพยายามตั้งชื่อ variable เป็น reserved keyword จะได้ error:

let this = "hey you"; // Uncaught SyntaxError: Unexpected token 'this'

Case Sensitivity

JS variables case sensitive ตัวแปร 2 ตัวนี้อ่านเหมือนกัน แต่ต่าง case:

  • helloThere
  • hellothere

ใน JS world นับเป็น 2 ตัวแปรคนละตัว ต้องระวัง lower/uppercase ตอน declare และ reference

เริ่มต้น variable ด้วย uppercase ได้ แต่ pattern ยอดนิยมคือ camelCase — ตัวแรกของคำแรก lowercase, คำต่อๆ ไป uppercase:

let aGoodRuleOfThumb