A statement starting with the function
keyword is treated as a function declaration and must be followed by a name that is a valid identifier.
An anonymous function expression starts with the word function
, but since there is no name, it can't be used where it might be confused with a function declaration. In most cases, the grouping operator is used to indicate a function expression:
(function() {
/...
}());
or
(function() {
/...
})();
You can also do:
var foo = function() {
}();
In all of the above, the function
keyword isn't at the start of the statement so it's treated as the start of a function epxression. A name isn't required and the function can be immediately called.
It's the same with !function...
. The parser sees the !
and says "what follows is an expression". When it gets to function
it knows it's the start of a function expression.
Using !function…
instead of (function…)
saves a single character, and possibly creates a bit of confusion as it's a less common way to write a function expression.