0

I have a simple question.

I've found this code, and i don't know this statement

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

why put ! before a function?

i've found this on bootstrap.js file, and i really want to know.

Thanks!

Kevin Ji
  • 10,479
  • 4
  • 40
  • 63
Paulo Mendonça
  • 635
  • 12
  • 28

2 Answers2

2

It is a duplicate as nnnnnn mentioned. What the code is doing is executing the anonymous function while passing window.jQuery as a parameter, which will be referenced as $ inside the function. This allows the use of $ to reference jQuery without conflicting with any other library that might use the dollar sign.

This is a more readable version of the code:

(function($){
    // here, $ references jQuery and any variable or function 
    // declared here cannot be overridden outside of this function
})(window.jQuery)
Community
  • 1
  • 1
Tibo
  • 988
  • 7
  • 9
-1

The ! will always parse the statement as being true if the statement is not able to be parsed.

You can see this by using,

javascript:alert(!function(){}())

Where the resulting response is true

Web Develop Wolf
  • 5,996
  • 12
  • 52
  • 101
  • 4
    _"if the statement is not able to be parsed."_ - Huh? Ignoring for now that it is an expression, not a statement, what do you mean by "not able to be parsed"? Code that can't be parsed can't be executed... – nnnnnn Jul 16 '13 at 22:31
  • @nnnnnn: Open up developer tools/firebug and try running `function() { alert('a'); }()` in there. It gives a syntax error. Now try `!function() { alert('a'); }()` -- it should alert and display `true`. Wrapping the function in parentheses also works. `(function(){ alert('a'); })()` – mpen Jul 16 '13 at 23:54