I was reading JS sources from Twitter — on my way to improve my JS knowledge base, when I came across the strange way of calling anonymous function:
!function( $ ) {
...
}( window.jQuery );
... and this works! :)
It's obvious to everyone, that this:
function ( $ ) { ... } ( window.jQuery )
does not work (Syntax error), while this one is correct:
(function ( $ ) { .... })( window.jQuery )
Can anyone please explain this magic (why case with !function
works)?
When the keyword function
is met in a statement position (as the first token in a statement), the function declaration is expressed as a function statement. Function statements are hoisted to the top of the scope, cannot be immediately invoked and must have a name.
When the keyword is met in an expression position (i.e. not as the first token in a statement, in your example !
is the first token), the function declaration is expressed as a function expression, which may be anonymous and returns the value of the newly created function. Since it returns the value of the newly created function, you may immediately invoke it by adding parenthesis after it.
Wrapping the declaration inside parenthesis does the same but is more common than prefixing it with a !
or +
:
(function () {
...
})();