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
1 | alert(foo()); // ERROR! foo wasn't loaded yet |
Example: Function Declaration
1 | alert(foo()); // Alerts 5. Declarations are loaded before any code can run. |
Function Declaration
1 | 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
1 | var foo = function bar() { ... } |
- Anonymous Function Expression
1 | var foo = function() { ... } |
foo()
can be called only after creation.