14

Is there difference between :

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

and :

(function($) {
     /*..........*/
})(jQuery);
Ahmed
  • 1,666
  • 17
  • 23
  • 1
    You will find many people do things for no good reason. This is almost certainly one of those times. (Or it could have been auto-generated as part of a build-script.) – Alexander O'Mara Mar 20 '16 at 05:57
  • 6
    Looks like someone didn't understand what they are doing. – Felix Kling Mar 20 '16 at 06:00
  • Do you mean there is no difference ? – Ahmed Mar 20 '16 at 06:08
  • I mean it doesn't make sense to wrap one inside the other. Of course there is an obvious difference between the two: One passes a value as first argument and the other doesn't. – Felix Kling Mar 20 '16 at 06:10
  • My question is there difference between (function(){/*…*/})(); and (function($){/*…*/})(jQuery); – Ahmed Mar 20 '16 at 06:11
  • the difference is an anonymous function called without parameters, and an anonymous function called with parameters(in this case the jQuery object) – winner_joiner Mar 20 '16 at 06:16
  • 2
    Maybe this is what you really want to know? [Why define an anonymous function and pass it jQuery as the argument?](http://stackoverflow.com/q/10371539/218196) – Felix Kling Mar 20 '16 at 06:26
  • In the example you have posted, the outer function can completely be omitted, it is plain redundant. About the inner function, it provides you a function scope, and ensures `$` refers to `jQuery`. – Gras Double Mar 20 '16 at 20:03
  • `why they used (function(){}() twice in the code below?` **&&** `I'm not asking about why they put one inside the other one .. I am asking if there is any difference between` Thats quite confusing what you are asking imho... – A. Wolff Mar 25 '16 at 23:21

8 Answers8

13

Other people explained what the difference is, but not why you use the latter.

The $ variable is most often used by jQuery. If you have one script tag that loads jQuery and another that loads your code, it's perfectly fine. Now throw prototype.js into the mix. If you load prototype.js and then jQuery, $ will still be jQuery. Do it the other way around and now $ is prototype.js.

If you tried to use $ on such a page, you'd likely get errors or weird behavior.

There are many questions on StackOverflow about this problem. Plugins shouldn't assume much about the page they're loaded in, so they use this pattern defensively.

Brigand
  • 84,529
  • 20
  • 165
  • 173
3

i am asking if there is difference between (function(){//})(); and (function($){//})(jQuery);

A little difference. In case of (function($){/*…*/})(jQuery); and absense of jQuery you'll get an error message immeditally after page loads. It's a simpler to detect jquery absense or incorrect order of scripts inclusion, when jquery-based code included before jQuery.

In case of (function(){/*…*/})(); you'll get an error message when code inside this construction actually call one of jQuery methods. It's harder to detect this error, but on the other side you can include your jquery-based scripts before jquery.

I prefer first case.

mbeloshitsky
  • 327
  • 1
  • 6
2

The second form, (function($){/*…*/})(jQuery); can be slightly safer when working in an environment where you don't (or can't) strictly enforce what code gets put on your site.

I used to work on a large site with a lot of third-party ads. These ads would often unsafely inject their own version of jQuery and occasionally they would override jQuery's global $ object. So, depending on how we wrote our code, we might be calling methods that no longer existed or had slightly different behaviour from what we expected. This could be impossible to debug, since some ads would never appear in our area or were excluded from our environment. This meant we had to be extremely protective of scope, inject our dependencies before any ad code had a chance to load, namespace anything that had to be global and pray no ad screwed with us.

Andrew
  • 14,204
  • 15
  • 60
  • 104
2

Other answers are quite fragmented so I'd like to give a more detailed answer for the question.

The main question can be self-answered if you understand..

What does (function(argument){ /*...*/ })(value); mean?

It's a quick hand version of:

var tempFunction = function(argument){
  /* ... */
}
tempFunction(value);

Without having to go through the hassle of conjuring up a new terrible name for a function that you will only call once and forget. Such functions are called anonymous functions since they aren't given a name.

So (function(){/*...*/})() is creating a function that accept no argument and execute it immediately, while (function($){/*...*/})(jQuery) is creating a function that accept one argument named $, and give it the value of jQuery.


Now that we know what the expression means, surely the first think on our mind is

"Why?". Isn't $ jQuery already?

Well, not exactly. We can never be sure. $ is an alias of jQuery, but other libraries can also use the same alias. As user @FakeRainBrigand already pointed out in his answer, prototype.js also use $ as its alias. In such cases, whichever library assigns its value to $ later wins out.

The practice of (function($){...})(jQuery) is very similar to an alias import in other programing languages. You are explicitly telling the system that your function:

  1. Requires an object/library named jQuery, and
  2. Within your function, $ means jQuery.

So even when someone include a new library later that override the alias $ at the global level, your plugin/framework still works as intended.

Because javascript is so... "flexible" in variable assignment, some people (including me) go as far as doing things like

var myApplication = (function($, undefined){ ... })(jQuery);

Apply the same understanding, it is easy to interpret the second argument part as: assign nothing to the variable undefined. So we can be sure that even if some idiot assigned a value to undefined later, our if(checkVariable === undefined){} won't break. (it's not a myth, people really do assign values to undefined)


When is it commonly used in javascript?

This anonymous function practice is most commonly found in the process of providing encapsulation for your plugin/library.

For example:

var jQuery = (function(){
  var publicFunction = function(){ /* ... */}
  var privateFunction = function(){ /* ... */}

  return {
    publicFunction : publicFunction
  }
})();

With this, only jQuery.publicFunction() is exposed at the global scope, and privateFunction() remains private.

But of course, it is also used any time you simply want to create a function, call it immediately, and throw it away. (For example as a callback for an asynchronous function)


For the bonus question

why they used (function(){}() twice in the below code?

Well, most likely because they don't know what they're doing. I can't think of any reason to put nested function in like that. None at all.

Community
  • 1
  • 1
AVAVT
  • 7,058
  • 2
  • 21
  • 44
1

(function(){/*...*/})(); does not set $ as reference to jQuery within IIFE and (function($){/*...*/})(jQuery); sets $ or other parameter name; e.g.; (function(Z){/*...* Z("body") where Z : jQuery*/})(jQuery); as reference to jQuery within IIFE

guest271314
  • 1
  • 15
  • 104
  • 177
1

The they are both closures. The first is just an anonymous function that will fire any well formatted code that is inside immediately. The second is the jQuery closure. It is how the jQuery library initiates it wraps its code in the JQuery object and exposes it isn't the $ symbol.

(function(){}()) // this is a closure

(function($){}(jQuery)) // is a closure that wraps the executed code inside of the jQuery returned object and exposes it via the $.
andre mcgruder
  • 1,120
  • 1
  • 9
  • 12
  • a closure is a variable defined outside a given function that is used inside a said function. – dandavis Mar 20 '16 at 06:49
  • These are [self-executing functions](https://en.wikipedia.org/wiki/Immediately-invoked_function_expression). A [closure](https://developer.mozilla.org/en/docs/Web/JavaScript/Closures) is a function returning a function, so that the latter has access to the scope of the former. – Gras Double Mar 20 '16 at 20:08
  • [Self-Executing Anonymous Functions]("http://markdalgleish.com/2011/03/self-executing-anonymous-functions/) – andre mcgruder Mar 21 '16 at 03:12
1

With this (function(){/*…*/})();, you are not passing any argument to the inner function, while with this (function($){/*…*/})(jQuery); you are passing jQuery as argument to the inner function and expecting its value as $(which means, you will be able to use jQuery inside the inner function).

Ex:

(function($){
  $(document).ready(function() {
    console.log('all resources loaded');
  })
})(jQuery);
1

They both are examples of Immediately Invoked Function Expression. In that sense, there is no difference between (function(){/*…*/})(); and (function($){/*…*/})(jQuery);. So no benefits are gained by wrapping (function($){/*…*/})(jQuery); inside (function(){/*…*/})();

A new execution context is created when a function is executed. So when (function(){/*…*/})(); is executed a context is created. Again when (function($){/*…*/})(jQuery); is executed, another context is created. Since the first context is not used (i.e. no variables are declared inside it), I don't see any advantages gained by the wrapping.

(function() { // <-- execution context which is not used
  (function($) { // <-- another execution context
    "use strict";
     /*..........*/
  })(jQuery);
})();
th1rdey3
  • 4,176
  • 7
  • 30
  • 66