Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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 is a named/anonymous function expression?
  • What is a declared function?
  • How do browsers deal with these constructs differently?

What do the responses to a similar question (var functionName = function() {} vs function functionName() {}) not get exactly right?

like image 428
Faisal Vali Avatar asked Jun 18 '09 15:06

Faisal Vali


2 Answers

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.

like image 121
Khon Lieu Avatar answered Sep 28 '22 06:09

Khon Lieu


Function Declaration

function foo() { ... } 

Because of function hoisting, the function declared this way can be called both after and before the definition.

Function Expression

  1. Named Function Expression

    var foo = function bar() { ... } 
  2. Anonymous Function Expression

    var foo = function() { ... } 

foo() can be called only after creation.

Immediately-Invoked Function Expression (IIFE)

(function() { ... }()); 

Conclusion

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.

like image 37
geniuscarrier Avatar answered Sep 28 '22 07:09

geniuscarrier