JS 引擎在执行代码前会先做「变量实例化」:var 声明的变量提前分配、值为 undefined;函数声明 function foo(){} 连同函数体整体提升。这就是为什么 var x = 1 之前访问 x 不报错而是 undefined,以及「先调用后定义函数」能跑通。
let / const 不会提升(准确说会进入 TDZ 暂时性死区):声明之前访问直接 ReferenceError,这是 ES6 刻意的设计,逼迫「先定义后使用」。函数表达式 const f = function(){} 只提升变量名、不提升函数体,与函数声明的差异常成为 bug 源。
console.log(a); // undefined(var 提升了,值还没赋) var a = 1; console.log(b); // ReferenceError: Cannot access 'b' before initialization let b = 1; // let/const 有暂时性死区 TDZ sayHi(); // 正常执行(函数声明整体提升) function sayHi() { console.log('hi'); } sayBye(); // TypeError: sayBye is not a function var sayBye = function () { console.log('bye'); };