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

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

    Variables using the let keyword should only be available within the scope of the block and not available in an outside function...

    Each variable that you are declaring in that manner is not using let or var. You are missing a comma in the variables declaration.

    It is not recommended to declare a variable without the var keyword. It can accidentally overwrite an existing global variable. The scope of the variables declared without the var keyword become global irrespective of where it is declared. Global variables can be accessed from anywhere in the web page.

    function first() {
       let a = 10;
       let b = 10;
       let c = 10;
       var d = 20;
       second();
    }
    
    function second() {
       console.log(b + ", " + c); //shows "10, 10"
       console.log(a); //reference error
       console.log(d); //reference error
    }
    
    first();

提交回复
热议问题