When a local (inner) function is declared in JavaScript, there are two options:
Declaring with var
keyword, assigning to the variable:
(function() {
var innerFunction1 = function() { ... };
innerFunction1();
}());
Declaring just with the function
keyword, without assigning to variable:
(function() {
function innerFunction2() { ... };
innerFunction2();
}());
I can see one advantage of the second: the function can be declared below the code which calls it so it is easier to separate private functions from the code actually executed.
Which of them is better and why?
Actually there are 3 ways to declare a function:
Function declaration: A Function Declaration defines a named function variable without requiring variable assignment. Function Declarations occur as standalone constructs and cannot be nested within non-function blocks. ex: function innerFunction1 () { };
Function expression:: A Function Expression defines a function as a part of a larger expression syntax (typically a variable assignment). Functions defined via Function Expressions can be named or anonymous:
a. Using an anonymous function - var innerFunction1 = function() { };
b. Using a named function - var innerFunction1 = function myInnerFunction () { };
Function constructor: A Function Constructor defines a function dynamically using the Function( ) constructor. Note that the function body is passed to the function as a string argument. var innerFunction1 = new Function (arg1, arg2, ... argN, functionBody)
The third method is not recommended because passing the function body as a string may prevent some JS engine optimizations, and it is prone to errors.
The differences between function declaration and function expression are subtle and you should choose whichever method suits your requirements best.
I use function expression where I need
Some differences between a function declaration and a function expression are:
Note: A function declaration can be easily turned into a function expression by assigning it to a var.
function foo() {}
alert(foo); // alerted string contains function name "foo"
var bar = foo;
alert(bar); // alerted string still contains function name "foo"
More Reading: