พวกมันแตกต่างกันในสามวิธี: scope, hoisting behavior และ reassignment.
js
() {
() {
a = ;
b = ;
c = ;
}
.(a);
.(b);
}
พวกมันแตกต่างกันในสามวิธี: scope, hoisting behavior และ reassignment.
() {
() {
a = ;
b = ;
c = ;
}
.(a);
.(b);
}
var คือ function-scoped, hoisted และ initialized เป็น undefined และสามารถ redeclare ได้ ซึ่งทำให้เกิด scope leaks ที่น่าประหลาดใจ — หลีกเลี่ยงlet คือ block-scoped ({ }), reassignable และอยู่ใน temporal dead zone จนกว่าถึง declaration line (การเข้าถึงก่อนหน้านี้จะ throw)const คือ block-scoped และ ไม่สามารถ reassign ได้ — แต่สังเกตว่า binding นั้นคงที่ ไม่ใช่ ค่า:const user = { name: "Ann" };
user.name = "Bob"; // ✅ allowed — mutating the object, not reassigning
user = {}; // ❌ TypeError — can't rebind `user`
ใช้ const เป็นค่า default; สลับไปที่ let เมื่อต้อง reassign เท่านั้น; อย่าใช้ var ในโค้ดใหม่ เลย ซึ่งจะทำให้ intent ชัดเจน ("สิ่งนี้จะไม่เปลี่ยน") และหลีกเลี่ยง scope leaks และ hoisting confusion ที่ var นำมา