Javascript function scoping and hoisting

后端 未结 18 2998
孤街浪徒
孤街浪徒 2020-11-21 04:20

I just read a great article about JavaScript Scoping and Hoisting by Ben Cherry in which he gives the following example:

var a = 1;

function b() {
    a =          


        
18条回答
  •  南方客
    南方客 (楼主)
    2020-11-21 05:13

    What is the bone of contention in this small snippet of code?

    Case 1:

    Include function a(){} definition inside the body of function b as follows. logs value of a = 1

    var a = 1;
    function b() {
      a = 10;
      return;
    
      function a() {}
    }
    b();
    console.log(a); // logs a = 1
    

    Case 2

    Exclude function a(){} definition inside the body of function b as follows. logs value of a = 10

    var a = 1;
    function b() {
      a = 10;  // overwrites the value of global 'var a'
      return;
    }
    b();
    console.log(a); // logs a = 10
    

    Observation will help you realise that statement console.log(a) logs the following values.

    Case 1 : a = 1

    Case 2 : a = 10

    Posits

    1. var a has been defined and declared lexically in the global scope.
    2. a=10 This statement is reassigning value to 10, it lexically sits inside the function b.

    Explanation of both the cases

    Because of function definition with name property a is same as the variable a. The variable a inside the function body b becomes a local variable. The previous line implies that the global value of a remains intact and the local value of a is updated to 10.

    So, what we intend to say is that the code below

    var a = 1;
    function b() {
      a = 10;
      return;
    
      function a() {}
    }
    b();
    console.log(a); // logs a = 1
    

    It is interpreted by the JS interpreter as follows.

    var a = 1;
    function b() {
      function a() {}
      a = 10;
      return;
    
    
    }
    b();
    console.log(a); // logs a = 1
    

    However, when we remove the function a(){} definition, the value of 'a' declared and defined outside the function b, that value gets overwritten and it changes to 10 in case 2. The value gets overwritten because a=10 refers to the global declaration and if it were to be declared locally we must have written var a = 10;.

    var a = 1;
    function b() {
      var a = 10; // here var a is declared and defined locally because it uses a var keyword. 
      return;
    }
    b();
    console.log(a); // logs a = 1
    

    We can clarify our doubt further by changing the name property in function a(){} definition to some other name than 'a'

    var a = 1;
    function b() {
      a = 10; // here var a is declared and defined locally because it uses a var keyword. 
      return;
    
      function foo() {}
    }
    b();
    console.log(a); // logs a = 1
    

提交回复
热议问题