So the difference is that function declarations are hoisted while function expressions are not. This can cause unexpected things to happen. Consider the following:
function foo() { return 'hi'; } console.log(foo()); function foo() { return 'hello'; }
What's actually printed to the console is hello
. This is due to the fact that the second definition of the foo()
function is hoisted to the top, making it the definition that is actually used by the JavaScript interpreter.
While at first this may not seem like a critical difference, in functional programming this can cause mayhem. Consider the following code snippet:
if (true) { function foo(){console.log('one')}; } else { function foo(){console.log('two')}; } foo();
When the foo()
function is called, two
is printed to the console, not one
!
Finally, there is a way to combine both function expressions and declarations. It works as follows:
var foo = function bar(){ console.log('hi'); }; foo(); // 'hi' bar(); // Error: bar is not defined
It makes very little sense to use this method because the name used in the declaration (the bar()
function in the preceding example) is not available outside the function and causes confusion. It would only be appropriate for recursion, for example:
var foo = function factorial(n) { if (n == 0) { return 1; } else { return n * factorial(n-1); } }; foo(5);