Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

!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.

like image 580
jondavidjohn Avatar asked Nov 29 '11 04:11

jondavidjohn


People also ask

What is the difference between using $( function and function?

So technically they are both the same. Not major difference between these two declaration. They used based on weather you use JavaScript then you should use $(document). ready declaration in other case you use jQuery library which is a part of JavaScript then you should use $(function) declaration.

What is function () {} in JS?

In JavaScript, a function allows you to define a block of code, give it a name and then execute it as many times as you want. A JavaScript function can be defined using function keyword.

What is the difference between a function and a method JavaScript?

Difference Between Function and Method:A JavaScript function is a block of code designed to perform a particular task. The javascript method is an object property that has a function value. A function can pass the data that is operated and may return the data. The method operates the data contained in a Class.

What does exclamation mark before function mean?

Exclamation mark makes any function always return a boolean. The final value is the negation of the value returned by the function.


2 Answers

  • 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...

base.js

var lol = function() {    alert(arguments[0]); } 

im-concat-to-base.js

(function() {     // Irrelevant. })(); 

jsFiddle.

Toss in a leading ; and she works...

jsFiddle.

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

jsFiddle.

like image 89
alex Avatar answered Sep 25 '22 13:09

alex


They're both ways of getting past the ambiguity in the grammar. Neither is more "hacky" than the other. It's just a style choice.

You could also do this:

0 + function( $ ) {   // ... } ( window.jQuery || window.ender ); 

Or:

parseInt(function( $ ) {   // ... } ( window.jQuery || window.ender ) ); 
like image 42
Pointy Avatar answered Sep 22 '22 13:09

Pointy