The following is a function statement. It can exist alone.
function foo(){
alert("This is an alert");
}
It can be 'called' (executed) like this:
foo();
The following is a function expression (such as anonymous function ** see edit at the bottom **).
As any other expression, it is like an rvalue, you can assign it to a variable
var f = function (){
alert("This is an alert");
};
which, then, can be 'called' (executed) like this:
f();
or you can use operators over it like this:
(function (){
alert("This is an alert");
})();
And note that this variable can now be passed as parameter to other functions! (i.e. we can pass functions as parameters).
Now, lets analyze this:
(function( window, undefined ) {
//blah blah blah -1
//blah blah blah -2
})(window);
this can be broken down into two:
var f = function( window, undefined ) {
//blah blah blah
};
f(window);
The function (assigned to f) takes 2 parameters, window
and undefined
. We are passing the 1st parameter as window
(which will be provided by the browser to the caller; it's a global object). Note that we are not passing any 2nd parameter. But since we are expecting 2nd param in the function but not passing any, the Javascript interpreter will assign an undefined
value (as defined in the interpreter) to it. So the variable (parameter) undefined
now contains undefined.
The main purpose of accepting these two values as parameters is to make the function independent of the global variables. (Just imagine what would happen if some JS script or a browser plugin changes undefined to something else!!)
Refer:
https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Functions
https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Expressions_and_Operators
EDIT:
As @FelixKling commented, function expressions need not be anonymous, they can have names.
var f = function foo(){
alert("This is an alert");
}
This is an interesting article about their usage.