Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 546
Hirvesh Avatar asked Sep 08 '12 16:09

Hirvesh


People also ask

What is IIFE immediately invoked function expression in JS?

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.

What is an IIFE immediately invoked function expression )? Can you give an example?

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.

What is IIFE jQuery?

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.

What is true regarding immediately invoked function expressions IIFE )?

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.


1 Answers

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

like image 197
jfriend00 Avatar answered Oct 26 '22 13:10

jfriend00