I am currently learning jQuery and following many tutorials, almost all of them are using (function(){}(); instead of (function($){}(jQuery); I know the purpose of them are to not create a global var. The thing is I notice I can still use jQuery object inside javascript self executed function, but I can't use them the other way. So why should I use jQuery's self exe func at all?
1 Answer
The premise: is simple comfortable to use $ instead of jQuery.
So $ is a simple shortcut of more verbose jQuery.
However $ is used also for other libraries or it could be used also as simple variable in other part of the project.
This is a trick in order to have the certainty of using the $ as jQuery, because the scope chain rule force javascript to take first the value of variable inside your scope, and only if there isn't take the value of the global scope.
Example:
// jQuery is loaded
console.log($ === jQuery) // true
window.$ = {thisIs:"myObject"};
console.log($ === jQuery); // false
(function($) {
console.log($ === jQuery); // true
})(jQuery);
$(i.e.jQuery) is one, for example. The point is to create as few as possible and then only those that truly are of global usefulness - like library variables. (And even jQuery has.noConflict()because its$shorthand might clash with other libraries.)