jondavidjohn jondavidjohn - 1 year ago 116
Javascript Question

!function(){ }() vs (function(){ })()

While reviewing some of the code written in the Twitter Bootstrap Javascript, it looks like they're calling immediately invoked anonymous functions like this:

!function( $ ) {


}(window.jQuery || window.ender);

Where I've traditionally seen this same thing accomplished this way:

(function($) {


})(window.jQuery || window.ender);

The first way seems a bit hacky, and I'm not sure if there is any benefit or reason for doing it this way rather than the second way? Note that I understand how it works, I'm looking to understand why they chose that way to do it.

Answer Source
  • One less character when minified.
  • The ! should handle where other JavaScript code is concatenated before this and doesn't have a trailing semi-colon.

There is not a huge difference. I would use whatever you were more comfortable with. You should probably toss something at the start of your example to avoid...


var lol = function() {


(function() {
    // Irrelevant.


Toss in a leading ; and she works...


...or a ! like the Twitter Bootstrap...


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download