IIFE (Immediately-invoked Function Expressions)

When developing Mobile Web Applications, even the seemingly marginal micro-optimizations can result in a noticeable performance improvement over time and, therefore should be implemented where possible. One could also argue (and rightly so) that this same principle applies when developing Web Applications on the Desktop; however, in the context of Mobile Web Experiences, such optimizations are essential, perhaps even obligatory on the developers part.

In a previous post from a few months back I discussed some of the benefits of function overwriting in JavaScript. One similar performance optimization I regularly employee is that of One-time function initializations.

Conceptually, an IIFE/em> is a rather simple pattern which can be broadly described as follows:

  1. An Immediate Function / Self-executing Function performs some initial test conditions.
  2. The Immediate Function returns an anonymous function which, in turn, returns the results of the test conditions. Alternately, the Immediate Function can just return the test condition results.
  3. The anonymous function returned is assigned to a function expression or, the test condition results are assigned directly.

An example in code illustrates just how simple this pattern is:

Practical implementation example:

Implementing Immediately-invoked Function Expressions are quite useful in many situations. Specifically, they are of most value when implemented for use-cases where conditions are too complex to assign to a variable directly and, when the conditions tested only need to be evaluated once, after which re-evaluating the condition would be redundant and unnecessary – such as certain feature detections.

As a general rule of thumb, if a condition or set of conditions can be tested once; that is, they are guaranteed to not change during the execution of the application and, the tests are too complex to maintain if directly assign to a variable, then implementing One-time function initializations are a small, yet simple and practical optimization.

{Sorry, Comments are currently Closed! }