{var a=1let b=2}{console.log(a);//输出1{console.log(b);//报错}``````javascript
functiontest(){let n =1;if(true){let n =2;}
console.log(n);//值不会被修改,输出1}test();if(1){let b =100;}
console.log( b );//错误 ReferenceError: b is not defined//因为let的块级作用域,所以b变量只存在与if内部```
var声明的变量的值可以被内部修改。
functiontests(){var n =1;if(true){var n =2;}
console.log(n);//值被函数内部修改,输出2}tests();if(1){var a =100;}
console.log( a );//输出100,因为var没有块级作用域,这里a会成为全局变量
在同一个块级作用域,var可以声明多次,let只能声明一次
{var a=2var a=3let b=2let b=3
console.log(a)//a=3
console.log(b)//报错,//Uncaught SyntaxError: Identifier 'b' has already been declared}
提升是指无论 var 出现在一个作用域的哪个位置,这个声明都属于当前的整个作用域,在其中到处都可以访问到。
{
console.log(a)//a=2var a=2
console.log(b)8//let&const.html:33 Uncaught ReferenceError: b is not defined at let&const.html:33let b=3}