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

1

7

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);
Cavalry answered 8/9, 2012 at 16:14 Comment(0)
L
15

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

Langmuir answered 8/9, 2012 at 16:16 Comment(1)
lovely answer my friend :-) Thank you! :-)Cavalry

© 2022 - 2024 — McMap. All rights reserved.