Why do some variables declared using let inside a function become available in another function, while others result in a reference error?

前端 未结 8 1122
说谎
说谎 2021-01-30 03:45

I can\'t understand why variables act so strange when declared inside a function.

  1. In the first function I declare with let the variabl

8条回答
  •  孤独总比滥情好
    2021-01-30 04:15

    In the function first(), variables band c are created on the fly, without using var or let.

    let a = b = c = 10; // b and c are created on the fly
    

    Is different than

    let a = 10, b = 10, c = 10; // b and c are created using let (note the ,)
    

    They become implicit global. That's why they are available in second()

    From documentation

    Assigning a value to an undeclared variable implicitly creates it as a global variable (it becomes a property of the global object) when the assignment is executed.

    To avoid this, you can use "use strict" that will provide errors when one use an undeclared variable

    "use strict"; // <-------------- check this
    
    function first() {
       /*
        * With "use strict" c is not defined.
        * (Neither is b, but since the line will be executed from right to left,
        * the variable c will cause the error and the script will stop)
        * Without, b and c become globals, and then are accessible in other functions
        */
       let a = b = c = 10;
       var d = 20;
       second();
    }
    
    function second() {
       console.log(b + ", " + c); //reference error
       console.log(a); //reference error
       console.log(d); //reference error
    }
    
    first();

提交回复
热议问题