What are IIFEs in JavaScript?

What are IIFEs in JavaScript?

Hey everyone! Hope you are doing okay :)

So, one day I was just scrolling through my YouTube recs when I came across Why IIFE appears in JavaScript interviews by Hitesh Choudhary, got curious because I had not heard of an acronym as IIFE in JS before. Hence, began my rabbit hole into what actually is an IIFE.

If you're also hearing this first time while reading this, I hope you learn a thing or two and if you already know what it is, maybe you'll brush up your knowledge about it? Anyway, let's start!

What you'll learn:

  • What are IIFEs
  • Varied Syntax of IIFEs
  • Use cases

Immediately Invoked Function Expression (pronounced iffy) is a JavaScript function that is executed as soon as it is defined. If you're thinking "duh, that's what the name says as well but what is it actually??", to answer your question, we'll look at what an IIFE actually looks like.

(function() {
  statements
})();

Let's see what this means:

The function part of the IIFE is function() { statements } enclosed within the () grouping operator. Now, HOW is enclosing this function in a pair of parenthesis helping us:

  • It creates a lexical scope, ensuring that variables defined within this scope are not accessible anywhere else in the file
  • Prevents polluting the global scope, this is a good coding practice.

So as soon as the compiler sees the opening parenthesis and the function() keyword, it is clear that a function has been defined and everything defined within that block remains private to that block only.

The pair of parenthesis at the end (); is what makes the compiler 'immediately invoke' the function. These 2 parts of the above code syntax generally make up an IIFE.

Variations in the syntax

We can use the IIFE syntax in various ways.

1. Arrow functions:

We can use arrow functions in IIFE like we usually do, but make sure the function is enclosed in a grouping operator ().

Example:

(() => {
    //statements
})();

2. Naming a function:

(function myIIFEFunction(){
    //statements
})();

Here's the catch, you cannot call myIIFEFunction() later in the file anywhere. However if you would like to access what the function is returning then you can simply assign the IIFE to a variable and use it later. Like this:

var myFirstIIFE = (function myIIFEFunction(){
    return 3;
})();

console.log(myFirstIIFE); //logs 3

Moreover, you can also use async functions in an IIFE like this:

(async() => {
   //statements
})();

// OR

(async function(){
  //statements
})();

Use Cases

By now, you probably have some idea of where you can use an IIFE, let's go through them!

1. Prevent polluting the global namespace

Polluting a global namespace means declaring all the variables with global scope i.e., they are accessible anywhere in the file. Example:

var variableOne = 1;
var VariableTwo = 3;

//rest of the code

If a variable is declared inside a block, then its scope will end the moment the block ends. That variable will be eligible for garbage collection because it cannot be used anymore. When it comes to globally scoped variables, they are collected only when the global scope ends. This way, variables that are unnecessarily declared in the global scope, only add to the computing power and hence, should be avoided.

In today's JavaScript (specifically after ES6), there has been a surge in using the keyword let and const to create block-scopes. This is why IIFEs might not be as common now as they used to be.

2. Async functions

await is a keyword that can only be used within an async function. Using it outside would result in a Syntax Error. IIFEs have been used widely in this case because it serves the purpose of privatisation of await. One thing to keep in mind is to handle exceptions inside the IIFE itself. For example:

(async () => {
  try {
        await something();
} catch (err) {
        console.log(err)
}
})();

3. Others

Other than the above uses IIFEs are used in:

  • Closures which are used in creating in private data by wrapping them.
  • Module Pattern. It is a design pattern in JS which encapsulates data stored within to prevent leaks in global scope and collision with the developer's variables.

Now, that we have seen what are IIFEs, different ways they can be written and their use-cases, you will be able to work with one.

The use of IIFEs have decreased over the past few years because of increasing compatibility with block scopes. However, with IIFE you can actually return something. So now you know when you can use it!

Thank you for reading!

Resources:

Why IIFE appears in JavaScript interviews

Understanding JavaScript IIFEs Like a Boss

MDN Docs

Did you find this article valuable?

Support Neha Badiani by becoming a sponsor. Any amount is appreciated!