This is the fifth day of my participation in the August More text Challenge. For details, see: August More Text Challenge

Let the const

There are only two types of variable declaration commands in ES5: var and function

In ES6, in addition to var, function, add let, const, class, import, a total of six

  1. Let is a new declaration command in ES6 that is similar to the var keyword in ES5

  2. Variables declared by let are valid within the code block

    {
        let a = 0
        var b = 1
    }
    console.log(b) / / 1
    console.log(a) // ReferenceError
    // This indicates that a variable declared by a let is valid only in the code block in which it resides
    Copy the code

    The let command works well in for loops

    var a = [];
    for (var i = 0; i < 10; i++) {
      a[i] = function () {
        console.log(i);
      };
    }
    a[6] ();/ / 10
    Var "I" = "I"; var "I" = "I"; var "I" = "I"
    
    var b = [];
    for (let j = 0; j < 10; j++) {
      b[j] = function () {
        console.log(j);
      };
    }
    b[6] ();/ / 6
    // the value of j is declared by let. The current value of j is only valid in the round of the loop. The value of j is actually a new variable each time, so the output is 6
    Copy the code
  3. The let command does not allow repeated declarations

    // SyntaxError
    function test1() {
      let a = 10
      var a = 1
    }
    // SyntaxErrot
    function test2() {
      let a = 10
      let a = 1
    }
    // SyntaxError
    function test3(a) {
        let a = 1
    }
    Copy the code
  4. Temporary dead zone

    // ReferenceError
    console.log(a)
    let a = 0
    Copy the code

    A variable declared by the let command in the same block of code cannot be used before the declaration. Reference errors are reported

    In a code block, a variable is not available before it is declared, which is syntactically called the temporal dead zone (TDZ).

  5. Const and let function like a property. They are valid only in the current code block and cannot be repeated

    A const declaration must assign an initial value and cannot change its value

    const a = 1
    a = 2 // TypeError
    const b // SyntaxError
    Copy the code
  6. Let and const variables are promoted

    The following code lets repeat the declaration with a syntax error, but console.log will not print properly until the error is reported

    The variable has been improved

    let a = 1
    console.log(a)
    let a = 2 // SyntaxError
    Copy the code

    But because of the temporary dead zone, we cannot use the variable before the declaration

    console.log(a) // undefined
    console.log(b) // ReferenceError
    
    var a = 2
    let b = 2
    Copy the code

    Note: The definition of a variable is divided into three stages: creation -> initialization to undefined -> assignment

    Let creation is promoted, but initialization is not

    Var creation and initialization are promoted

    Function creation, initialization, and assignment are promoted

Block-level scope

  1. There are only global scopes and function scopes in ES5

    // Global scope
    var a = 0
    
    function test() {
        // Function scope
        var a = 1
    }
    Copy the code

    Existing problems

    var a = 0
    function test() {
        console.log(a)
        if(false) {
            var a = 1
        }
    }
    test() // undefined
    
    Copy the code

    In function scope, the var a command variable is promoted, causing a to be undefined

  2. ES6 specifies that {} is internally a separate block-level scope

    The outer code block is not affected by the inner code block

    The outer scope cannot read variables in the inner scope

    An inner scope can define variables of the same name in an outer scope

    {{
      let a = 0
      {
          let a = 1
          {
              console.log(a) / / an error}}}}Copy the code
  3. The advent of block-level scope eliminates the need for widely used immediate execution functions

    / / IIFE
    (function () {
      var tmp = ...;
      ...
    }());
    
    // Block level scope
    {
      lettmp = ... ; . }Copy the code

Function declaration

  1. ES5 states that functions can only be declared in global scope and function scope

    / / a
    if (true) {
      function fn() {}}/ / 2
    try {
      function fn() {}}catch(e) {
    }
    Copy the code

    This is an illegal declaration, but in order to be compatible with older code, the browser does not follow this rule and will run without error, but in strict mode it will report an error

    // ES5 strict mode
    'use strict';
    if (true) {
      function fn() {}}/ / an error
    Copy the code
  2. ES6 introduces block-level scope, which explicitly allows functions to be declared at block-level scope

    // ES6 strict mode
    'use strict';
    if (true) {
      function fn() {}}/ / is not an error
    Copy the code
  3. ES6 specifies that function declarations in the block-level scope cannot be referenced outside the scope

    function fn() { 
        console.log('outside')} (function () {
      if (false) {
        // Declare the function again
        function fn() { 
            console.log('inside')
        }
      }
      fn()
    }())
    Copy the code

    In ES5, inside is printed because fn in the if block is promoted to the self-executing function header

    In ES6, it prints outside, because fn declared in the if block cannot be accessed outside the scope, and only externally declared FN can be performed

    Because of the wide variation in behavior, ES6 states that browsers can override this and behave in their own way

    1. Allows functions to be declared in block-level scope
    2. Function declarations are similar to var, that is, promoted to the head of the global scope or function scope
    3. Also, function declarations are promoted to the head of their block-level scope

    The above example code may not work in the Chrome environment because the actual code that runs is as follows

    function fn() { 
        console.log('outside')} (function () {
      var fn = undefined
      if (false) {
        function fn() { 
            console.log('inside')
        }
      }
      fn()
    }())
    // Uncaught TypeError: fn is not a function
    Copy the code