What is the difference between these two functions/approaches?

前端 未结 4 1511
南旧
南旧 2020-12-06 07:10

I use only jQuery for writing JavaScript code. One thing that confuses me is these two approaches of writing functions,

First approach



        
4条回答
  •  情深已故
    2020-12-06 07:57

    function myFunction() {}
    

    ...is called a "function declaration".

    var myFunction = function() {};
    

    ...is called a "function expression".

    They're very similar; however:

    • The function declaration can be declared after it is referenced, whereas the function expression must be declared before it is referenced:

      // OK
      myFunction();
      function myFunction() {}
      
      // Error
      myFunction();
      var myFunction = function() {};
      
    • Since a function expression is a statement, it should be followed by a semi-colon.

    See Function constructor vs. function declaration vs. function expression at the Mozilla Developer Centre for more information.

提交回复
热议问题