4 Practical Use Cases for IIFEs in JavaScript
By: Amy J. Andrews
Tags: Web Development, Programming, Javascript Development, Javascript Tips, JavaScript

4 Practical Use Cases for IIFEs in JavaScript

Photo by Markus Spiske on Unsplash

You knew the concept of IIFE, right?

Simply put from its full name, Immediately Invoked Function Expression, it’s a function that runs as soon as it’s defined.

IIEFs are well-known for protecting variables scope. But what does it actually mean? And what are practical use cases of IIEFs?

You will know the answers in this article. Let’s dive into it.

Closures

A variable defined in an IIFE can’t be accessed from the outside. Or when you use let or const to declare a variable, it can only be accessed in the enclosing block.

However, you probably need to modify the values of those variables sometimes. Is it possible? Yes, it is.

Here’s how:

You know closures, right? Closures give you the ability to access an outer function’s scope from an inner function. Creating a closure is nothing but defining a function inside another function and expose it.

When combining a closure with an IIFE, you get two great benefits.

The first is that the scopes of variables are secured to prevent unexpected behaviors.

The second one, you can modify variables inside a function from the outside. It sounds like we are breaking the first benefit. Except we don’t. Because you can’t modify the variables’ values directly but only from an exposing function. And it’s safe.

const user = (function() {

let name = ‘anonymous’; return {

getName: _ => name,

setName: newName => name = newName

};

})(); console.log(user.getName()) // anonymous

user.setName(‘Amy’);

console.log(user.getName()); // Amy

The name variable is private, which means we can only access it inside the user IIFE. However, since we use a closure here, we can modify it from the outside via exposing setName() method.

Alias Global Variables

Using many JavaScript libraries can cause conflicts because some of them might export an object with the same name.

Let’s say you’re using jQuery. We all know it export $ as its main object. So, if there’s any library in your dependencies using $ as its exported object as well, a conflict will occur.

Fortunately, you can use IIFEs to solve this problem by applying the aliasing technique:

(function ($) {

// You’re safe to use jQuery here

})(jQuery);

By wrapping your code inside an IIFE that takes jQuery as an argument, we will make sure that the $ symbol now refers to jQuery , not other libraries.

Secure Variables Scope

ES6 has introduced let and const to define variables safer. Using var might lead to an unexpected result because its scope is vulnerable.

But what if the production environment hasn’t supported ES6 yet? Or somehow you can’t make use of let and const ?

Don’t worry. You still have IIFE, Immediately Invoked Function Expression, to serve the same purpose.

(function () {

var greeting = ‘Good morning! How are you today?’;

console.log(greeting); // Good morning! How are you today?

})(); console.log(greeting); // error: Uncaught ReferenceError: greeting is not defined

As you can see in the example above, what happens in the IIFE scope, stays in the IIFE scope. You can’t use the variable defined inside IIFE from the outside.

Loop Index

Executing asynchronous tasks inside a loop might lead to an unexpected result.

Take using setTimeout() for example:

for (var i = 0; i < 3; i++) {

setTimeout(_ => console.log(`We’re at ${i}`), 100);

}

You expect the result should be:

We’re at 0

We’re at 1

We’re at 2

But it actually is:

We’re at 3

We’re at 3

We’re at 3

Why? Because the console.log() calls in the example will only run after each 100ms . The loop might finish before that time, which means the i index has actually reached 3 . As the result, all the console.log() will print the final result of i , 3 .

We can solve this problem by putting the setTimeout() call into an IIFE:

for (var i = 0; i < 3; i++) {

(function(index) {

setTimeout(_ => console.log(`We’re at ${index}`), 100);

})(i);

}

The result now is correct:

We’re at 0

We’re at 1

We’re at 2

However, this is the age of ES6, we can use let keyword to simplify the code:

for (let i = 0; i < 3; i++) {

setTimeout(_ => console.log(`We’re at ${i}`), 100);

}

Final Thought

An IIFE is a good way to secure the scope. You can use IIFEs to prevent global variables’ definition issues, alias variables, protect private data, and avoid conflicts of using many libraries that export the same object name.

While you can replace some IIFE usages with ES6 features, you still should learn about IIFE to understand clearly how scope works in JavaScript. And besides, you can’t adapt legacy projects to ES6 immediately. So, IIFEs still play a big role.

Hope you enjoy this article.