What is the difference between a function expression vs declaration in JavaScript?

This question already has an answer here:

  • var functionName = function() {} vs function functionName() {} 31 answers

  • They're actually really similar. How you call them is exactly the same.The difference lies in how the browser loads them into the execution context.

    Function declarations load before any code is executed.

    Function expressions load only when the interpreter reaches that line of code.

    So if you try to call a function expression before it's loaded, you'll get an error! If you call a function declaration instead, it'll always work, because no code can be called until all declarations are loaded.

    Example: Function Expression

    alert(foo()); // ERROR! foo wasn't loaded yet
    var foo = function() { return 5; } 
    

    Example: Function Declaration

    alert(foo()); // Alerts 5. Declarations are loaded before any code can run.
    function foo() { return 5; } 
    


    As for the second part of your question:

    var foo = function foo() { return 5; } var foo = function foo() { return 5; } is really the same as the other two. It's just that this line of code used to cause an error in safari, though it no longer does.


    Function Declaration

    function foo() { ... }
    

    Because of function hoisting , the function declared this way can be called both after and before the definition.

    Function Expression

  • Named Function Expression

    var foo = function bar() { ... }
    
  • Anonymous Function Expression

    var foo = function() { ... }
    
  • foo() can be called only after creation.

    Immediately-Invoked Function Expression (IIFE)

    (function() { ... }());
    

    Conclusion

    Crockford recommends to use function expression because it makes it clear that foo is a variable containing a function value. Well, personally, I prefer to use Declaration unless there is a reason for Expression.


    Regarding 3rd definition:

    var foo = function foo() { return 5; }
    

    Heres an example which shows how to use possibility of recursive call:

    a = function b(i) { 
      if (i>10) {
        return i;
      }
      else {
        return b(++i);
      }
    }
    
    console.log(a(5));  // outputs 11
    console.log(a(10)); // outputs 11
    console.log(a(11)); // outputs 11
    console.log(a(15)); // outputs 15
    

    Edit: more interesting example with closures:

    a = function(c) {
     return function b(i){
      if (i>c) {
       return i;
      }
      return b(++i);
     }
    }
    d = a(5);
    console.log(d(3)); // outputs 6
    console.log(d(8)); // outputs 8
    
    链接地址: http://www.djcxy.com/p/17264.html

    上一篇: 为什么使用命名函数表达式

    下一篇: JavaScript中的函数表达式与声明之间有什么区别?