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);
})();
BASHHello 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");
BASHHello John
You can also create IIFEs using arrow functions.
JAVASCRIPT((name) => {
const message = `Hello ${name}`;
console.log(message);
})("John");
BASHHello 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);
BASHUncaught 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!
- Managing PHP Dependencies with Composer
- Getting Started with Electron
- Git Tutorial: Learn how to use Version Control
- How to Serve Static Files with Nginx and Docker
- How to Set Up Cron Jobs in Linux
- Best Visual Studio Code Extensions for 2022
- How to deploy a Deno app using Docker
- Getting Started with Deno
- Getting Started with Sass
- Getting User Location using JavaScript's Geolocation API
- Creating a Twitter bot with Node.js
- Using Axios to Pull Data from a REST API