Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
160
rated 0 times [  165] [ 5]  / answers: 1 / hits: 17186  / 8 Years ago, mon, january 23, 2017, 12:00:00

I understand that the following is shorthand for $( document ).ready():



$(function() {
console.log( ready! );
});


I also understand what an anonymous JS function is, but does jQuery does anything special when it's called using one. I.e.:



(function() {
console.log( ready! );
})($);


Is the latter just a normal anonymous JS function that uses jQuery (ie. it will NOT be considered shorthand for $(document).ready() and so will execute immediately)?



I feel this MUST have been asked before, but I can't find it if it has.


More From » jquery

 Answers
9

As you mentioned, the former is indeed a shorthand for $(document).ready().
As for the latter, this is just an Immediately Invoked Function Expression.



(function ($) {
console.log('ready');
})(jQuery);


This function is simply an anonymous function which receives a parameter named $. The function is immediately invoked with some value (in this case jQuery) as the parameter.



IIFEs can also be used to isolate scopes and to avoid global variables in web applications which contain multiple JavaScript files. In this case a parameterless IIFE could be used:



(function () {
// x is only accessible within this IIFE
var x;
// do something...
})();


For more information regarding Immediately Invoked Function Expression, see this question: What is the purpose of a self executing function in javascript?


[#59238] Friday, January 20, 2017, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
frederickmohamedw

Total Points: 21
Total Questions: 123
Total Answers: 105

Location: The Bahamas
Member since Tue, Apr 27, 2021
3 Years ago
;