7

I get all of the plugins code except for one line, and due to the way search engines work I cant actually search for my question.

The question is what in the hell is this:

(!function($) {/*....*/})(jQuery);

Why does it say !functions($)?? I'm guessing for the same effect of the $.noConflict() but isn't that why we just use (function($) {/*...*/})(jQuery); it just wraps the dollar sign to our function block. I am completely aware that I could be way off base here, I'm still intermediate in jQuery/js.

If someone could please enlighten me on the effect of the NOT operator before the function statement, i would greatly appreciate it.

Edit: It would appear that i overlooked bootstrap not having (!function($) ... ) but just being !function($)... but you guys helped me in realizing it is just an alternative to ()

dhazelett
  • 336
  • 1
  • 3
  • 10

1 Answers1

4

So there a couple things going on here. Everything is being wrapped in an anonymous function that is executed right away. This is to create a scope for the library so that when the author declares functions and variables they are are not global by default.

With me so far. Ok next thing is the whole ($){...}(jQuery) thing. What is going on here is the author is passing the jQuery library into the anonymous wrapper function as a parameter called $. So in the scope of the anonymous function he can use $ to reference jQuery as you would expect. This is more of a best practices thing because 99% of the time jQuery is already defined as $ in the global scope, but its considered bad form to refer to global variables within a functions scope, and thus he / she passes it in as a parameter.

Still there? The exclamation mark: there is a rule in Javascript that states the first line of a program MUST be an expression (ie not a function declaration aka statement). By prepending the ! the author is turning the declaration into an expression (that returns false). In this case however I don't think the ! is actually required because the declaration is wrapped in () and executed right away. (A function call is an expression)

Matthew
  • 12,892
  • 6
  • 42
  • 45
  • Indeed, it's already an expression; the `!` is redundant. It's an _alternative_ to wrapping the declaration in parens, but the author has done both for some reason. And I don't know what you're referring to when you talk about the first line of a program; indeed the vast majority of Javascript scripts I'm sure begin with statements. – Lightness Races in Orbit Feb 06 '12 at 12:27