The first one is, indeed, a shorthand for $( document ).ready()
, as pointed here.
But the second one is Immediately-Invoked Function Expression (IIFE), an anonymous function that is declared and immediately called.
In fact, the correct syntax (the argument is missing in your example) is:
(function($) {
//my $ object is local now
})(jQuery);
In this case, you're calling the anonymous function with an argument.
The main advantage of this pattern (IIFE) is: isolate your code (you can create as many variables as you want and it'll be restricted to your anonymous function scope, unless you return something). This pattern is used a lot to define "private" and "public" methods. Like this:
var myModule = (function() {
function privateFunction() { console.log("I can't be accessed from outside :("; }
var privateVar = "me too :(";
function publicFunction() { console.log("Hey! I'm here!"; }
/* expose what you want */
return {
publicFunction: publicFunction
}
})();
myModule.publicFunction(); //Hey! I'm here!
myModule.privateFunction(); //undefined;
You can also call it module pattern.
In your second example, you're calling the recently-created anonymous function with an argument, and your anonymous function receives that argument. This is a way of dependecy injection.
This way, you manipulate your global variable inside the function as local. Note that in the first example, we're passing a jQuery
object and manipulating it inside your function as $
. It's more difficult to someone override jQuery object, but, some script can re-assign the global dollar symbol, specially if you don't have full control of your app. This way, you're allways passing te jQuery
object and manipulating it as $
.
At the end, let me list some other advantages of passing parameters to a IIFE grabbed from here:
it's faster: JavaScript first lookup into the local scope (before
climbing up). It may improve performance a bit.
helps minification: minifier can now rename variables inside your
scope to a one letter word, reducing code size.