An explanation of what is going on and why...
In Javascript, you have function statements
and function expressions
. The two of them are similar, but not exact.
Function statement
function myTest() {return true;}
Function Expressions
var f = function() {return true;}
alert(f()); //
alert(function() { return true}); // Return value is used
// and even
(function(x, y) {
var z, x; // private variables, hidden from the outside scope
var r = x + y;
// Return value is ignored.
}(1, 2));
// The ! can be used to start a function expression too.
// This is totally legal Javascript, but it isn't in the normal
// "vernacular" of the langage
!function(x, y) {
var z, z1; // Private vars
// Do something with side effects
// Return value is ignored.
}(x, y);
Updated due to comments
//The following code works identical:
var v1 = (function(a, b) {return a+b}(1,2));
var v2 = (function(a, b) {return a+b})(1,2);
var v3 = function(a, b) {return a+b}(1,2)
I prefer the first form because it lets me use the block matching tools on my editor, and the f1
form is preferred by the sometimes useful programs JSLint and JSHint.
All create a function expression and then invoke it immediately. In this case, the parens are not needed by the Javascript compiler, but they serve as a very useful hint to the reader that this is not a normal assignment.
On the other hand, you must have something to tell the JS engine that you have a function expression instead of a function statement. The =
sign above works, but when there is no assignment, you need to start off with some kind of operator, be it (+!
!function(x, y) {alert(x, y)}(1, 2);
The leading operator makes it an expression. The ()
in the above examples force it to an expression as well.