1

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; }
guagay_wk
  • 26,337
  • 54
  • 186
  • 295
  • May I ask why the negative vote? Could you explain why so that I can improve? – guagay_wk Nov 04 '15 at 08:50
  • 5
    Possible duplicate of [Why use named function expressions?](http://stackoverflow.com/questions/15336347/why-use-named-function-expressions) – vaultah Nov 04 '15 at 08:50
  • for example if you want foo to be resolved in different functions based on config or environment. – webduvet Nov 04 '15 at 09:37

1 Answers1

1

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.

webduvet
  • 4,220
  • 2
  • 28
  • 39