They’re actually really similar. How you call them is exactly the same.The difference lies in how the browser loads them into the execution context.

Function declarations load before any code is executed.

Function expressions load only when the interpreter reaches that line of code.
Function expression has variable scope as well
If you want to pass function to another function, function expression must be used (because it’s a variable!)!

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
alert(foo()); // ERROR! foo wasn't loaded yet
var foo = function() { return 5; } 
Example: function declaration
alert(foo()); // Alerts 5. 
              // Declarations are loaded before any code can run.
function foo() { return 5; } 

0 commenti

Lascia un commento

Segnaposto per l'avatar