Javascript: what does this line mean?
!function ( $ )
Javascript: what does this line mean?
!function ( $ )
I'll bet a slightly more complete version would look like this:
!function ( $ ) {
// some code
}(jQuery);
Basically the above uses the !
operator to have the anonymous function be interpreted as a function expression that can then be immediately called. Take away the !
and you have an invalid function declaration (or function statement, depending on your prefered terminology) - invalid because it has no name. The more usual way to do this is by putting it in parentheses:
(function ( $ ) {
// some code
})(jQuery);
But some people like to save a character by using !
rather than parentheses.
One reason why you might use code like this is so that you can create some working variables that don't end up in the global scope. Or, from within the anonymous function, to create an object that is in the global scope but that has methods which can access private variables in the anonymous function's scope.
Regarding the $
argument, I'm just guessing that jQuery
would be passed as a parameter to the function since this is common when using the argument name $
. One reason you might do that is so that you can use another library that defines $
at the same time as using jQuery, yet use the $
for jQuery within this block.
I think we're missing some data, but I'm betting the piece is from a closure in a conditional statement or ternary.
var test = 'Testing!';
(!function ( $ ) {
alert($);
return false;
}(test) ? alert("bad") : alert("good"));