
ES6之前Javascript没有块级作用域。在{}中定义的变量,它的作用域范围是包含它的函数或者脚本。也就是说,没有块级作用域。

let语句定义了块级作用域。let使得能够在块级作用域内声明变量,只能在定义它的作用域范围内使用。


var声明的变量具有函数作用域。

let重定义变量将报错:

在ES6中,let定义的变量也会提升,然而,如果在定义变量之前引用了变量,将得到ReferenceError.
function do_something() { console.log(foo); let foo = 2; } do_something(); /* Exception: ReferenceError: can't access lexical declaration 'foo' before initialization do_something@Scratchpad/1:12:3 @Scratchpad/1:16:1 */
在switch语句中,let定义也不能重名:
switch (x) { case 0: let foo; break; case 1: let foo; // TypeError for redeclaration. break; } /* Exception: TypeError: redeclaration of let foo @Scratchpad/1:16 */
let vs var##
var a = 5; var b = 10; if (a === 5) { let a = 4; var b = 1; console.log(a); // 4 console.log(b); // 1 } console.log(a); // 5 console.log(b); // 1
let绑定变量在局部作用域中
for (let i = 0; i < 10; i++) { console.log(i); } console.log(i); /* Exception: ReferenceError: i is not defined @Scratchpad/1:13:1 */
控制语句##
如果你需要赋值表达式作为条件表达式可以写成下面这种形式(加括号):
if ((x = y)) { /* statements here */ }
falsy值###
false、undefined、null、0、NaN、""在布尔运算中为false
本文整理自:
MDN
网友评论