Javascript function scoping and hoisting

后端 未结 18 3009
孤街浪徒
孤街浪徒 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:08

    From my piece of knowledge, hoisting happens with the variable declaration and function declaration, for example:

    a = 7;
    var a;
    console.log(a) 
    

    What happens inside JavaScript's engine:

    var a;
    a = 7;
    console.log(a);
    // 7
    

    Or:

    console.log(square(7)); // Output: 49
    function square(n) { return n * n; }
    

    It will become:

    function square(n) { return n * n; }
    console.log(square(7)); // 49
    

    But assignments such as variable assigment, function expression assignment will not be hoisted: For example:

    console.log(x);
    var x = 7; // undefined
    

    It may become like this:

    var x;
    console.log(x); // undefined
    x = 7;
    

提交回复
热议问题