The “Immediately Invoked Function Expression” or iife is a common thing to see in modern JavaScript applications.

I always had a good idea of what it did but today I saw a strong use case that made me appreciate it more.

Here’s what an iife looks like:

(function () {
  // .. do some stuff
 }());
 

A common problem in JavaScript (especially in older code such as jQuery) is that variable names are hoisted to the top of their scope, which can sometimes be the global namespace. This can lead to naming collisions especially when common variable names are being used and external libraries are being brought in.

An iife is self-executing function, which means that code inside an iife is scoped to the iife itself and will not be hoisted. This idea of function scoping is key to JavaScript. This is a technique to keep code modular and keep dependencies separated.

An iife can hold the use strict directive, which is a nice feature that prevents sloppy JavaScripting. read more here But some older libraries would not function under the conditions of use strict. Therefore, by declaring it in an iife, the directive does not make it outside the function scope and only applies to the indented code.