JavaScript hoisting function vs function variable

前端 未结 4 897
礼貌的吻别
礼貌的吻别 2021-01-22 17:34

Here is my javascript code :

    console.log(a);
    c();
    b();            
    var a = \'Hello World\';
    var b = function(){
        console.log(\"B is ca         


        
相关标签:
4条回答
  • 2021-01-22 18:09

    A Function Declaration will be hoisted along with its body.

    A Function Expression not, only the var statement will be hoisted.


    This is how your code "looks" like to the interpreter after compiletime - before runtime:

     var c = function c(){
          console.log("C is called");
     }
    
     var a = undefined
     var b = undefined
    
     console.log(a); // undefined at this point
     c(); // can be called since it has been hoisted completely
     b(); // undefined at this point (error)
    
     a = 'Hello World';
     b = function(){
         console.log("B is called");
     }
    

    KISSJavaScript

    0 讨论(0)
  • 2021-01-22 18:23

    At the time you are calling b is not defined yet. Your b is a variable which contains function, and the time you are accessing b it has not been defined yet.

    0 讨论(0)
  • 2021-01-22 18:24

    Function Expression:

      var b = function(){
            console.log("B is called");
        }
    

    Function Declaration:

    function c(){
        console.log("C is called");
    }
    

    Function Expressions loads only when the interpreter reaches that line of code.On the other side the function Declaration, it'll always work. Because no code can be called until all declarations are loaded.

    Read more about Function Declaration and Function Expression

    0 讨论(0)
  • 2021-01-22 18:32

    Because declare a function with Function Expression create an anonymous function unless you explicitly provide a name :

    var b = function() {}   // anonymous function 
    

    and differently when you declare a function with Function Declaration, you set a name :

    function c() {}   // c function 
    
    0 讨论(0)
提交回复
热议问题