它们在三个方面不同:scope、hoisting behavior 和 reassignment。
js
function demo() {
if (true) {
var a = 1; // function-scoped — leaks out of the if-block
let b = 2; // block-scoped — only exists inside { }
const c = 3; // block-scoped, can't be reassigned
}
.(a);
.(b);
}
关键区别
var是 ,被提升并初始化为 ,可以重新声明。这会导致意外的泄漏 — 避免使用。
js
const user = { name: "Ann" };
user.name = "Bob"; // ✅ allowed — mutating the object, not reassigning
user = {}; // ❌ TypeError — can't rebind `user`
基本规则
默认使用 const;仅在必须重新赋值时切换到 let;在新代码中永远不要使用 var。这使意图明确("这不会改变"),并避免 var 带来的作用域泄漏和变量提升混淆。
