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

They're actually really similar. How you call them is exactly the same, but the difference lies in how the browser loads them into the execution context.
function declarations loads before any code is executed. 
While function expressions loads 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
But if you call a function declaration, it'll always work. Because no code can be called until all declarations are loaded. 
ex. Function Expression
alert(foo()); // ERROR! foo wasn't loaded yet
var foo = function() { return 5; } 
ex. Function Declaration
alert(foo()); // Alerts 5. Declarations are loaded before any code can run.
function foo() { return 5; } 
Via: http://stackoverflow.com/questions/1013385/what-is-the-difference-between-a-function-expression-vs-declaration-in-javascrip

Comments