I've got the following code which I know is an IIFE. However, I've never been able to grasp what the (jQuery) and ($) is. I know it's got something to do with passing a reference of jQuery into the IIFE, but could someone explain me clearly the purpose of them? Thank you for you help and time :-)
(function ($) {
//code
})(jQuery);
An IIFE (Immediately Invoked Function Expression) is a JavaScript function that runs as soon as it is defined. The name IIFE is promoted by Ben Alman in his blog.
An Immediate-Invoked Function Expression (IIFE) is a function that is executed instantly after it's defined. This pattern has been used to alias global variables, make variables and functions private and to ensure asynchronous code in loops are executed correctly.
An IIFE, or Immediately Invoked Function Expression, is a common JavaScript design pattern used by most popular libraries (jQuery, Backbone. js, Modernizr, etc) to place all library code inside of a local scope.
An Immediately-invoked Function Expression is a way to execute functions immediately, as soon as they are created. IIFEs are very useful because they don't pollute the global object, and they are a simple way to isolate variables declarations.
$
is an argument to a function. jQuery
is what is being passed as that argument when the function is invoked.
Think of it like this:
function init($) {
// code can use $ here as a shortcut for jQuery
// even if $ has a different definition globally or isn't defined globally
}
init(jQuery);
Except for the fact that this example creates a global symbol init
, the execution of this and your IIFE are identical. Both define a function and immediately call it.
$
is an argument to the function. jQuery
is what is passed as that argument. This serves to define $
as a shortcut for jQuery
while inside that function without affecting the global definition of $
. There can also sometimes be a slight performance advantage because symbols defined locally (either as local variables or as named arguments) can be slightly faster to access than global symbols.
The advantage of the IIFE is that no new global symbols are defined. Other than that, it's identical in execution to this code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With