A Quick Look at IIFEs in JavaScript - thinklab - thinklab

A Quick Look at IIFEs in JavaScript

IIFEs or ‘Immediately-Invoked Function Expressions’ (sometimes called Auto-Executing Functions), sound complicated, but they’re actually pretty straightforward to understand.

A Simple Example

You’ll be used to declaring JavaScript functions like this:

function myName(name) {
  console.log('Hello ' + name);
}

You would then make a separate call to your function to invoke it.

The difference with IIFEs, is that they are invoked immediately after they are setup. If we modify our function declaration from above, you can see how this would look:

(function myName(name) {
  console.log('Hello ' + name);
}('Jay'));

Differences to note are:

  • The entire function is wrapped within parens
  • Right after the closing bracket, the function is invoked using another set of parens, along with a value for our example ‘name’ argument.

Granted, this is a somewhat contrived example, but it should give you a good idea of how the syntax works and the differences an IIFE has compared with a regular function declaration.

Syntax Note

One thing to note about IIFEs, is that they can be either anonymous or named. Therefore, the following modification to our function would also be valid:

(function(name) {
console.log('Hello ' + name);
}('Jay'));

Benefits

One benefit of using anonymous IIFEs, is that they’re able to pass, and make reference to, global objects (such as window, document, jQuery) within their local scope, without the need to access the global scope chain. This reduces scope lookup, since JavaScript doesn’t need to go up the scope chain to look for properties outside of the function’s local scope.

(function(window, document){
  // the global window and document objects can now be reference from within this local scope
}(window, document));

Another example of using anonymous IIFEs and global objects that you may be familiar with, is scoping jQuery using the $ alias to avoid library conflicts:

(function($){
  // jQuery can now be referenced from within this local scope using $
}(jQuery));

 

Brought to you by Christian Redecen-Davies

Designer. Traveller. Photographer. Purveyor of fine pixels since 1999.

See all posts by Christian Redecen-Davies

Comments