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

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

Leave a Comment