javascriptfunctionfunction-expressionjavascript-function-declaration

What are good situations to use function expression instead of function declaration?


I will prefer to use function declaration all the time because I can place the function anywhere on the source file. If I use function expression, the function has to be placed at the top of the source file.

Are there good situations to use function expression instead of function declaration?

//Function declaration
function foo() { return 5; }

//Anonymous function expression
var foo = function() { return 5; }

Solution

  • All variables declarations are hoisted on the top of the scope and all function definitions are as well hoisted on the top of the scope. Therefore

    console(foo()); // prints foo
    function foo(){return 'foo'};
    

    but

    console(foo()); // complain foo is not function, it is undefined
    var foo = function(){return 'foo'};
    

    the second example is identical to this:

    var foo;
    console.log(foo());
    foo = function(){}
    

    The reasons for using the second expression would stem from your programming logic. for example:

    var foo = MY_ENV_VAR ? function(){return true} : function(){return false}
    

    or run the following example for better understanding:

    var bar;                                                                                                                                                                                                
    
    if (true) {
      function foo(){return 'foo'};
      bar = function(){return 'hey'};
    } else {
      function foo(){return 'another'};
      bar = function(){return 'bar'};
    }
    console.log(foo());
    console.log(bar());
    

    the first log will be another because JS compiler puts the function declaration on the top of the scope and the second declaration just overwrites the first one. While the second log outputs the result of the function assigned in the if statement , which will be hey.