3

Possible Duplicate:
What does the exclamation mark do before the function?
What does !function ($) { $(function(){ }) }(window.jQuery) do?

what is the meaning of "!function($){}(window.jQuery)" ?

<script type="text/javascript">
    !function($){
        //some codes here
    }(window.jQuery)
</script>

this js orginal code url:http://twitter.github.com/bootstrap/assets/js/bootstrap-dropdown.js

Community
  • 1
  • 1
linjuming
  • 2,117
  • 4
  • 23
  • 32

1 Answers1

6

The ! at the beginning of the line turns your function into a function expression, it has the basically same effect¹ as the more popular IIFE forms:

(function($){}(window.jQuery));
//which in turn is the same as
(function($){})(window.jQuery);

Then it is immediately invoked by passing window.jQuery as the $ argument. This is useful to be able to use $ referencing jQuery inside the function independently of the page having jQuery in noConflict mode or not.

This approach is very common (and recommended) when developing plugins for 3rd-party use.

Little more explained: Function declarations can't be part of an expression, hence when you put the function keyword inside a () or precede it with a unary operator, it is interpreted as a function expression.

¹ There is a subtle difference between (function(){}()) and !function(){}(): while the parentheses simply evaluate the function to a function object in the form of a function expression, the unary ! will do the same thing and flip the return value of the function expression. As you're not assigning this value to anything, it will simply be discarded.

It is 1 byte in load time vs the cost of a ! operation in execution time. Both of these shouldn't take more than a fraction of milli/microsecond. It is mostly a matter of coding style preference.

Fabrício Matté
  • 69,329
  • 26
  • 129
  • 166
  • So it is a trick to save a single byte (one `!` versus a `()` pair) over the more common construct? – mu is too short Jan 12 '13 at 03:00
  • @muistooshort Basically that, yes. Some even prefer `+function(){}()`, there are some other unary operators that can be used to make a function be part of a expression. – Fabrício Matté Jan 12 '13 at 03:01
  • very detailed explanation, thank you very much. – linjuming Jan 12 '13 at 03:17
  • @linjuming No problem. `=]` Felix's links are also very complete, I expected this question to have a duplicate but wasn't aware that there would be such extended answers for the same case. I guess yours is a little more special as it also includes jQuery plugin authoring, `=]` oh wait, there is even a question for twitter bootstrap itself, wow. – Fabrício Matté Jan 12 '13 at 03:19