How to use Immediately Invoked Function Expressions (IIFE) in JavaScript

Updated onbyAlan Morel
How to use Immediately Invoked Function Expressions (IIFE) in JavaScript

Because JavaScript is such a dynamic language, there are many different design patterns that you can use when writing your code.

One of these design patterns is utilizing what is called an immediately invoked function expression, or IIFE.

In this post, we'll learn what an IIFE is, why you would use it, and how to use it.

What is an IIFE in JavaScript?

An IIFE is a function that is immediately invoked after it is created. It is a design pattern that is used to create a new scope for your code.

Because the function is self-contained, the variables and functions that are defined within the function are not accessible outside of the function, ensuring that you don't pollute the global namespace.

How do you create an IIFE in JavaScript?

Now that we understand what an IIFE is, let's learn how to create one.

The syntax for creating an IIFE is as follows:

JAVASCRIPT
(function() { const message = "Hello World"; console.log(message); })();
BASH
Hello World

The first thing to note is that the function is wrapped in parentheses. This is what allows the function to be immediately invoked.

The second thing to note is that the function is immediately invoked by adding a pair of parentheses after the function.

Keep in mind that you can also pass arguments into the function, just like you would with any other function.

JAVASCRIPT
(function(name) { const message = `Hello ${name}`; console.log(message); })("John");
BASH
Hello John

You can also create IIFEs using arrow functions.

JAVASCRIPT
((name) => { const message = `Hello ${name}`; console.log(message); })("John");
BASH
Hello John

Remember, because IFFEs create their own scope, variables defined within the function are not accessible outside of the function.

JAVASCRIPT
(function() { const message = "Hello World"; })(); console.log(message);
BASH
Uncaught ReferenceError: message is not defined

Conclusion

In this post, we learned what an IIFE is, why you would use it, and how to use it.

IIFEs can be a useful design pattern to use when you want to create a new scope for your code and don't want to pollute the global namespace.

Thanks for reading!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.