Immediately-Invoked Function Expression (IIFE) In JavaScript - Passing jQuery

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);

Answers:

Answer

$ 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.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.