I have gotten so used to jQuery that I have completely forgotten about looking more into Javascript. Now, I am trying to fix that. So what exactly is the jQuery equivalent to:
(function() {
// ...
}());
I have seen this around quite a lot and was wondering what it does exactly and I think the best way for me to understand it is if I see its jQuery equivalent provided that it has one. If there isn’t one, then a brief explanation would suffice or a link pointing to what I should be reading up on to understand what is going on with the code above would do. Thank you in advance.
IIFE (Immediately Invoked Function Expression) is a JavaScript function that runs as soon as it is defined.
It is a design pattern which is also known as Self-Executing Anonymous Function and contains two major parts. The first is the anonymous function with lexical scope enclosed within the Grouping Operator (). This prevents accessing variables within the IIFE idiom as well as polluting the global scope.
The second part is creating the immediately executing function expression (), through which the JavaScript engine will directly interpret the function.
I can’t tell you whether jQuery has an equivalent, as I don’t generally use it an awful lot.
Sorry Alex, but jQuery has no systems in place that are equivalent to IIFE’s, primarily because there’s no simpler way to do IIFE’s than is already achieved natively with vanilla JavaScript.
Yes, that jQuery ready method is quite different from IIFE’s, because the former delays the execution of the code until after the DOM has been loaded, whereas the latter runs immediately. Due to the good-practice technique of placing scripts at the end of the body, just before the </body> tag, no delay is necessary in your code anymore.