Back to: JavaScript Tutorial For Beginners and Professionals
IIFE (Immediately Invoked Function Expressions) in JavaScript
In this article, I am going to discuss IIFE (Immediately Invoked Function Expressions) in JavaScript with Examples. Please read our previous article where we discussed JavaScript Anonymous Function. At the end of this article, you will understand what are JavaScript Immediately Invoked Function Expressions and when and how to use this in JavaScript.
IIFE in JavaScript
IIFE stands for Immediately Invoked Function Expressions. As the name says it is nothing but a function. IIFE is actually an anonymous function that is invoked immediately as soon as the function is created. Let us understand IIFE with some examples. In the following example, we created one function called Init and as soon as it is created, we call the function, so that it is executed immediately.
<html> <head> <title>Immediately Invoked Function Expressions (IIFE) in JavaScript</title> </head> <body> <script> function Init() { console.log("Init Function Executed"); } Init(); </script> </body> </html>
Let us see, how to convert the above function to IIFE. As we already discussed, IIFE is a self-executing anonymous function. Please have a look which shows how to create an IIFE in JavaScript. To turn a normal anonymous function into a self-executing function, we simply cover the anonymous function in parentheses and then add a set of parentheses and a semicolon after it.
The complete is given below.
<html> <head> <title>Immediately Invoked Function Expressions (IIFE) in JavaScript</title> </head> <body> <script> (function () { console.log("IIFE Executed "); })(); </script> </body> </html>
Output: When you run the above code, you will get the following output in the browser console window.
IIFE Executed
What is IIFE in JavaScript?
The Immediately-Invoked Function Expression (IIFE) in JavaScript is a way to execute functions immediately as soon as they are created. In other words, IIFE is a function expression that immediately invokes after the function definition is complete automatically. The parenthesis () plays an important role in the IIFE pattern. In JavaScript, parenthesis cannot contain statements; it can only contain an expression.
JavaScript IIFE Features:
- IIFE functions are anonymous functions wrapped in parentheses
- IIFE functions are called with the parameters immediately after the last parentheses enclosing the anonymous function
- IIFE functions are immediately invoked as soon as it is created. So cannot be called later
- IIFE functions take zero or any number of arguments
Uses of IIFE (Immediately Invoked Function Expressions) in JavaScript:
IIFE does not pollute/ infect the global variables and they are a simple way to segregate variables declarations. That makes it easy to hunt defects and we have a maintenance code. Let us understand this with an example.
In the below example, we have declared the variable x within the body as well as within the IIFE function. The global variables are also immediately executed. As we discussed IIFE does not pollute or affect the global variables, so in this case, within the IIFE function, it will print its own x value i.e. 15, and in the body (outside of the IIFE function), it will print the global x value i.e. 5.
<html> <head> <title>Immediately Invoked Function Expressions (IIFE) in JavaScript</title> </head> <body> <script> var x = 5; (function () { var x = 15; console.log("IIFE x : "+ x); })(); console.log("Global x : "+ x); </script> </body> </html>
Output:
Can we access the variables which are declared within the IIFE globally?
No, the variables declared within the IFFE are private and hence you can not access those variables outside the IFFE function. If you try to do so, then you will get an error. For better understanding, please have a look at the below code.
<html> <head> <title>Immediately Invoked Function Expressions (IIFE) in JavaScript</title> </head> <body> <script> (function () { var x = 15; console.log("IIFE x : "+ x); })(); console.log("Global x : "+ x); //Error </script> </body> </html>
Output:
So, the biggest advantage of IIFE in JavaScript is that with IIFE you can create self-contained initialization anonymous functions and these anonymous function variables do not mix with the global scope variables.
Creating namespaces using IIFE in JavaScript:
Another benefit of using IIFE is, it allows us to create namespaces (logical containers) for grouping objects and these namespaces can have closures or objects inside them. Let us understand this with an example.
We have four closures as shown in the below image. What we want it, we want to group these four closures into two namespaces. ContractEmployee and PermanentEmployee into one namespace and Student and StudentReport into another namespace.
So, basically, we want to group our closures into logical containers called namespaces. Here, we created two namespaces (EmployeeNamepscae and StudentNamespace). The EmployeeNamepscae contains the ContractEmployee and PermanentEmployee closures. The StudentNamespace contains the Student and StudentReport closures. Let see how to achieve this.
Step1:
Create two variables as shown below which is going to be act as our namespaces.
var EmployeeNamespace = {};
var StudentNamespace = {};
Step2:
Initialize the EmployeeNamespace. First, create an anonymous function and as part of the anonymous function, place the two closures and then convert it into an IIFE as shown below. Again, the anonymous function becomes a closure and hence we also need to write the return statement and mention the two objects (ContractEmployee and PermanentEmployee) which we want to make public.
Then again, Initialize the StudentNamespace with the IIFE which contains the Student and StudentReport closures as shown below. Again, the anonymous function becomes a closure and hence we need to write the return statement and mention the two objects (Student and StudentReport) which we want to make public.
Now you can create the object using the namespace and can access the respective functions as shown in the below image.
The Complete code of the above example is given below.
<html> <head> <title>Creating Namespaces using JavaScript IIFE</title> </head> <body> <script> var EmployeeNamespace = {}; var StudentNamespace = {}; EmployeeNamespace = (function() { function ContractEmployee() { var _AddContractEmployee = function(){ console.log("Contract Employee Added"); } return { AddContractEmployee : _AddContractEmployee } }; function PermanentEmployee() { var _AddPermanentEmployee = function(){ console.log("Permanent Employee Added"); } return { AddPermanentEmployee : _AddPermanentEmployee } }; return { ContractEmployee, PermanentEmployee } }()); StudentNamespace = (function() { function Student() { var _AddStudent = function(){ console.log("Student Added"); } return { AddStudent : _AddStudent } }; function StudentReport() { var _GetStudentReport = function(){ console.log("Student Report"); } return { GetStudentReport : _GetStudentReport } }; return { Student, StudentReport } }()); var EmpContract = EmployeeNamespace.ContractEmployee(); EmpContract.AddContractEmployee(); var EmpPermanent = EmployeeNamespace.PermanentEmployee(); EmpPermanent.AddPermanentEmployee(); var stud = StudentNamespace.Student(); stud.AddStudent(); var studReport = StudentNamespace.StudentReport(); studReport.GetStudentReport(); </script> </body> </html>
Output:
So, the combination of closures and IIFE creates the namespace which logically organized our code.
Named IIFE in JavaScript
If required it is possible to name an IIFE. While less often seen, this pattern has several advantages, such as providing a reference that can be used for recursion and can make debugging simpler as the name is included in the call stack. For a better understanding, please have a look at the following example.
<html> <head> <title>JavaScript named IIFE example</title> </head> <body> <script> (function namedIIFE() { console.log("Named IIFE"); }()); </script> </body> </html>
Why we need JavaScript Immediately Invoked Function Expressions?
Sometimes we don’t want to have our function accessible/stored as a variable. We can create an Immediately Invoked Function Expression (IIFE for short) in JavaScript which will be executed as soon as it is created. The IIFE is also called self-executing anonymous functions. A self-executing anonymous function is a function that executes as soon as it’s defined. They have access to the surrounding scope, but the function itself and any internal variables will not be accessible from the outside.
Advantages of IIFE (Immediately Invoked Function Expressions ) in JavaScript:
- IIFE does not create unnecessary global variables and functions.
- Functions and variables created in IIFE do not conflict with other functions & variables even if they have the same name.
- Organize JavaScript code.
- Make JavaScript code maintainable
- The benefit of using self-executing anonymous functions is that the variables we create inside of them are destroyed when the function exits. In this way, we can avoid conflicts between variable names, and we avoid holding variables in memory after they’re no longer needed.
In the next article, I am going to discuss JavaScript Array Function with Examples. Here, in this article, I try to explain JavaScript Immediately Invoked Function Expressions with examples. I hope this JavaScript Immediately Invoked Function Expressions article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this JavaScript Immediately Invoked Function Expressions article.