The let/const keyword of es6

1. let

  1. The new keywords used to declare variables in es6. The variables declared by let are only valid at the block level in which they are located, and are aimed at the new block-level scope of es6

    if (true) {
          
          
    	let a = 1;
    }
    console.log(a);// a is not defined;
    
  2. Variables declared using let can only be declared once

  3. Special note: there are child scopes in a block-level scope, and the child scope can access the parent scope, but the parent scope cannot access the child scope

    if (true) {
          
          
    	let a = 1;
        if (true) {
          
          
            let b = 1;
            console.log(a); // 1
        }
        console.log(b); // b is not defined;
    }
    
  4. note:

    1. Variables declared with var do not have block-level scope characteristics, so the use of let variables can prevent loop variables from becoming global variables
    for (var i = 0; i < 3; i++) {
          
          
            
        }
        console.log(i); // 3 // 外面可以访问
    
    for (let i = 0; i < 3; i++) {
          
          
    
        }
        console.log(i); // i is not defined 外面不可以访问
    
    1. Variables declared with the let keyword do not have variable promotion

    2. Variables declared with the let keyword have temporary dead zone characteristics, that is, the variable declared by let is bound to the block-level scope, even if it has the same name as an external variable, there is no mutual relationship, so the following code will report an error.

      var a = 1;
      if (true) {
              
              
          console.log(a);// a is not defined
          let a;
      }
      

2. const

  1. A new keyword for declaring constants is added in es6, which means that the memory address stored in the variable cannot be modified

  2. Has all the advantages of let

  3. Features:

    1. Block-level scope
    2. No variable promotion
    3. Need to assign initial value
    4. Value cannot be modified
  4. note:

    ​ The constant declared by const only refers to the immutable value that it points to, but when the constant declared by const points to an object/array, although the point of the const constant may not be modified, the value of the object pointed to by it can be performed modify. Therefore const does not really protect the data from being changed. If you want the data not to be changed, you can take the following methods:

    • Object.freeze()Prevent data changes

    • Using the above method, any attempt to change the object will be blocked, and no error will be reported

      let obj = {
              
              
          uname: 'zt',
          age: 19
      }
      Object.freeze(obj);// 冻结对象obj
      obj.uname = 'zztt';// 试图修改对象obj但是被忽略,实则并没有修改对象obj的值
      

Guess you like

Origin blog.csdn.net/chen__cheng/article/details/114288492