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

前端 未结 8 1119
说谎
说谎 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:05

    Before calling things strange, let’s know some basics first:

    var and let are both used for variable declaration in JavaScript. For example,

    var one = 1;
    let two = 2;
    

    Variables can also be declared without using var or let. For example,

    three = 3;
    

    Now the difference between the above approaches is that:

    var is function scoped

    and

    let is block scoped.

    while the scope of the variables declared without var/let keyword become global irrespective of where it is declared.

    Global variables can be accessed from anywhere in the web page (not recommended because globals can be accidentally modified).

    Now according to these concepts let's have a look at the code in question:

     function first() {
       let a = b = c = 10;
       /* The above line means:
        let a=10; // Block scope
        b=10; // Global scope
        c=10; // Global scope
        */
    
       var d = 20; // Function scope
       second();
    }
    
    function second() {
       alert(b + ", " + c); // Shows "10, 10" //accessible because of global scope
       alert(a); // Error not accessible because block scope has ended
       alert(d); // Error not accessible because function scope has ended
    }
    

提交回复
热议问题