参考:https://www.cnblogs.com/fly_dragon/p/8669057.html
最近很多前端的朋友去面试被问到let和var的区别,其实阮一峰老师的ES6中已经很详细介绍了let
的用法和var
的区别。我简单总结一下,以便各位以后面试中使用。
ES6 新增了let
命令,用来声明局部变量。它的用法类似于var
,但是所声明的变量,只在let
命令所在的代码块内有效,而且有暂时性死区的约束。
var定义的声明可以提升到作用域的顶部。
- 例子:没定义的var变量就抛出异常
console.log("ud = ",xx);
结果:抛出异常
$ node src/test.js
E:\study\js\four\src\test.js:1
console.log("ud = ",xx);
^
ReferenceError: xx is not defined
at Object.<anonymous> (E:\study\js\four\src\test.js:1:21)
at Module._compile (internal/modules/cjs/loader.js:1137:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1157:10)
at Module.load (internal/modules/cjs/loader.js:985:32)
at Function.Module._load (internal/modules/cjs/loader.js:878:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)