Learn Immediately Invoked Function Expressions (IIFEs) in JavaScript

Today, we're focusing on a topic that often puzzles beginners: Immediately Invoked Function Expressions, or IIFEs (pronounced "iffy").

What is an IIFE?

An IIFE is a function that runs as soon as it is defined.

It stands for Immediately Invoked Function Expression.

The name might seem intimidating, but once you understand the concept, you'll see it's straightforward and can be helpful.

Quick Recap: Functions in JavaScript

Let's quickly review the basics of functions in JavaScript. A function is a block of code designed to perform a particular task. For example:

function sayHi() {
    console.log("Hello world! ✌️");
}

To run this function, you'd call it by its name followed by parentheses:

sayHi(); // Output: "Hello world! ✌️"

Structure of an IFFE

Can you guess what happens when you structure code this way?

(function() {
    console.log("Hello world! ✌️");
})();

This is what we call an IFFE, and it is made of two main parts:

  • The function expression is enclosed in parentheses. This part contains the function's logic.
  • The second set of parentheses at the end triggers the function's immediate execution.

When this code is run, Hello world! ✌️ is logged to the console just like before, but this time without explicitly calling the function on a new line.

Why Use an IIFE?

You might wonder, "Why the heck would I need a function that runs immediately?"

There are a few reasons, but the two big reasons I find myself using an IFFE are:

Single-use functions

I create and call a function only once directly after eg:

function sayHi() {
    console.log("Hello world! ✌️");
}
sayHi();

I will often find it cleaner to use an IFFE instead.

Variable Scoping

Variables declared in an IIFE are not visible outside its scope. This helps to avoid variable name conflicts.

(function() {
    var num = 10;
    console.log(num); // Output: 10
})();
// Log outside function scope:
console.log(num); // Output: ReferenceError: x is not defined

By having variables in the scope, we can also avoid global conflicts.

Named vs. Anonymous IIFEs

While our first encounter with IIFEs involves anonymous function expressions, knowing that IIFEs can also be named is essential.

Anonymous IIFEs

Anonymous IIFEs are those without a name.

They're defined and then immediately executed without any explicit function name. Like in our previous example:

(function() {
    var num = 10;
    console.log(num); // Output: 10
})();

The above code will immediately log 10 to the console.

Named IIFEs

Named IIFEs, on the other hand, have a function name. Here's how a named IIFE looks (again using a previous example):

(function sayHi() {
    console.log("Hello world! ✌️");
})();

The above code will immediately log Hello world! ✌️ to the console.

Just like the anonymous IIFE, this named IIFE will also log its greeting to the console immediately.

The function sayHi is still inaccessible from the outside, preserving the encapsulation we expect from IIFEs:

(function sayHi() {
    console.log("Hello world! ✌️");
})();
// Output: "Hello world! ✌️"

// Calling after the IFFE
sayHi();
// Output: Uncaught ReferenceError: sayHi is not defined

Why Use Named IIFEs?

When debugging, the main benefit of using a named IIFE over an anonymous one is stack trace clarity.

If an error occurs inside an IIFE, the stack trace will display the function name, making it easier to pinpoint the source of the problem.

Remember, the important thing about IIFEs is not whether they have a name, but the encapsulation they provide, the pollution they prevent, and their ability to execute immediately.

As with everything in coding, it's about using the right tool for the job!


Follow me on Twitter or connect on LinkedIn.

🚨 Want to make friends and learn from peers? You can join our free web developer community here. 🎉

JavaScriptJSIffe
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses; Lead Developer, Software Architect, Product Manager, CTO and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.