ES6声明(Let Const Var).(ES6 declaration (let const var))

一、变量提升

A、用var声明的变量,会在其作用域中发生变量提升,js默认给变量一个undefined值。

B、在ES6中使用let/const声明的变量,不存在变量提升过程。也就是说,在使用let/const声明的变量,声明前访问它,都会报错。

1 {
2     var value=10;
3     let count=10;
4 }
5 console.log(value);   //10
6 console.log(count);   //引用错误

二、暂时死区

if (true) {
    // 死区开始
    value = 10;
    console.log(value);
    // 死区结束
    let value;
}

三、重复声明

A、let 和 const 命令声明的变量不允许重复声明;

B、而使用var声明变量,可以多次重复声明一个同名变量,但最终变量的值为最后一次声明赋值的结果。

1 var a = 10;
2 var a = 'abc';
3 var a = 'last value';
4 console.log(a);  // last value

四、作用域

1 for (let i = 0; i < 10, i++) {
2     console.log(i);
3 }
4 console.log(i);  //var声明 则10 ; let声明  报错
1 var list=[];
2 for (var i = 0; i < 10; i++) {
3     list[i]=function(){
4         console.log(i);
5     }
6 }
7 list[5]();  //结果永远是10
1 var list=[];
2 for (let i = 0; i < 10; i++) {
3     list[i]=function(){
4         console.log(i);
5     }
6 }
7 list[5]();

五、const常量

  • 1   const声明的作用是:创建一个只读的常量,一旦声明不可改变
  • 2    和let声明一样,const声明的常量无法提升,也存在临时死区
  • 3    和let不同的是,const声明后必须赋值,否则会报错
const PI=3.14;
console.log(PI);
————————

1、 Variable promotion

A. Variables declared with VaR will be promoted in their scope. JS gives the variable an undefined value by default.

B. For variables declared with let / const in ES6, there is no variable promotion process. In other words, when a variable declared with let / const is accessed before declaration, an error will be reported.

1 {
2     var value=10;
3     let count=10;
4 }
5 console.log(value);   //10
6 console.log(count);   //引用错误

2、 Temporary dead zone

if (true) {
    // 死区开始
    value = 10;
    console.log(value);
    // 死区结束
    let value;
}

3、 Repeat declaration

A. Variables declared by let and const commands cannot be declared repeatedly;

B. Using VaR to declare a variable, you can declare a variable with the same name repeatedly, but the value of the final variable is the result of the assignment of the last declaration.

1 var a = 10;
2 var a = 'abc';
3 var a = 'last value';
4 console.log(a);  // last value

4、 Scope

1 for (let i = 0; i < 10, i++) {
2     console.log(i);
3 }
4 console.log(i);  //var声明 则10 ; let声明  报错
1 var list=[];
2 for (var i = 0; i < 10; i++) {
3     list[i]=function(){
4         console.log(i);
5     }
6 }
7 list[5]();  //结果永远是10
1 var list=[];
2 for (let i = 0; i < 10; i++) {
3     list[i]=function(){
4         console.log(i);
5     }
6 }
7 list[5]();

5、 Const constant

  • one     Const declaration is used to create a read-only constant, which cannot be changed once declared
  • two     Like the let declaration, const declaration constants cannot be promoted and there are temporary deadbands
  • three     Unlike let, const must be assigned a value after declaration, otherwise an error will be reported
const PI=3.14;
console.log(PI);