Possible Duplicate:
JavaScript: var functionName = function() {} vs function functionName() {}
Suppose we are inside a function and not in the global namespace.
function someGlobalFunction() {
var utilFunction1 = function() {
}
function utilFunction2 () {
}
utilFunction1();
utilFunction2();
}
Are these synonymous? And do these functions completely cease to exist when someGlobalFunction returns? Should I prefer one or the other for readability or some other reason?
They are mostly the same.
utilFunction1will only be available after it has been declared.utilFunction2is hoisted to the top of the function, so can be used before it is defined.Unless they are trapped in a closure, both will cease to exist when
someGlobalFunctionreturns.I prefer to use the method used to declare
utilFunction2, but it’s up to you.Declarations of the form
utilFunction2(which are called Function Declarations) have the benefit of being named (i.e. showing up asutilFunction2) in your-favourite-debuggerTM, where asutilFunction1(called Function Expressions) would just show up as an anonymous function.For completeness, you also have the form;
… which is called a named function expression, which has weird properties (and bugs (in older versions of IE)) of its own.