Function Declaration [ function functionName() {} ] vs. Function Expression [ var functionName = function() {} ]
I had previously thought function functionName() {} was syntactic sugar for var functionName = function () {}. There are some subtle differences in both which I am listing below :-
1) Function Declaration can be placed anywhere in the code. Even if it is invoked before the definition appears in code, it gets executed as function declaration is committed to memory or in a way it is hoisted up, before any other code in the page starts execution.
1) Function Declaration can be placed anywhere in the code. Even if it is invoked before the definition appears in code, it gets executed as function declaration is committed to memory or in a way it is hoisted up, before any other code in the page starts execution.
Take a look at the function below:
function outerFunction() {
function foo() {
return 1;
}
return foo();
function foo() {
return 2;
}
}
alert(outerFunction()); //displays 2
This is because, during execution, it looks like:-
function foo() { // first function declaration is moved to top
return 1;
}
function foo() { // second function declaration is moved to top
return 2;
}
function outerFunction() {
return foo();
}
alert(outerFunction()); //So executing from top to bottom,
//the last foo() returns 2 which gets displayed
Function Expression if not defined before calling, will result in error. Also, here the function definition itself is not moved to the top or committed to memory like in the function declarations. But the variable to which we assign the function gets hoisted up and undefined gets assigned to it.
Same foo() function using function expressions:-
function outerFunction() {
var foo = function() {
return 1;
}
return foo();
var foo = function() {
return 2;
}
}
alert(outerFunction()); //displays 1
This is because during execution, it looks like:-
function outerFunction() {
var foo = undefined;
var foo = undefined;
foo = function() {
return 1;
};
return foo ();
foo = function() { // this Function Expression is not reachable
return 2;
};
}
alert(outerFunction()); // displays 1
2) It is not safe to write Function declarations in non-function blocks like if because they won't be accessible
if(test) {
function x() { doSomething(); }
}
3) Named function expression like the one below, may not work in IE browsers < 9.
var today = function today() { // your code }
Having said that, named function expressions are better than anonymous function expressions. Why because,
- Named function expressions can invoke itself by the name, suppose if you want to do a recursion. You cannot invoke an anonymous function.
- Named function expressions are easier to debug.
- Named function expressions are more readable.
Comments
Post a Comment