What is the difference between the following lines of code?
//Function declaration function foo() { return 5; } //Anonymous function expression var foo = function() { return 5; } //Named function expression var foo = function foo() { return 5; }
What do the responses to a similar question (var functionName = function() {} vs function functionName() {}) not get exactly right?
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.
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; }
As for the second part of your question:
var foo = function foo() { return 5; }
is really the same as the other two. It's just that this line of code used to cause an error in safari, though it no longer does.
function foo() { ... }
Because of function hoisting, the function declared this way can be called both after and before the definition.
Named Function Expression
var foo = function bar() { ... }
Anonymous Function Expression
var foo = function() { ... }
foo()
can be called only after creation.
(function() { ... }());
Crockford recommends to use function expression because it makes it clear that foo
is a variable containing a function value. Well, personally, I prefer to use Declaration unless there is a reason for Expression.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With