IIFE stands for immediately invoked function expression it means self executable function. This function gets executed by itself without external call.
As javascript does not had private variables IIFE and closure are used together to create a private variables and methods.
(function (){
//Write some Logic
})();
Example:
function Greet() {
console.log("I am from Regular Function"); // Regular Function.
};
Greet();
(function() {
console.log("I am from IIFE"); // IIFE creation and execution.
})();
I am from Regular Function
I am from IIFE
An IIFE is a function that is called immediately after creating.
The most important use case for an IIFE is that of creating a new scope for your program or your library so that any changes to the global namespace have minimal or no effect on your code.
What is the use of IIFE ?
An IFFE actually enables your code to do the following:
- Executes automatically after the code has been compiled.
- Let’s you isolate internal functionality inside the IIFE scope.
- Promotes cleaner code and readability, since you can organize your IIFE as if they were application modules.
It is mainly used for data privacy. As you are aware of var is scoped to the function hence any data declared inside the iffy function cannot be accessed outside world.
What is the difference between a normal function expression and an IIFE in JavaScript?
A normal function simply includes a declaration and a definition but an IIFE is declaration, definition and invocation at the same time. As the name says Immediately Invoked Function Execution. Invoked right away.
- IIFE stands for immediately invoked function expression.
- Main use of IIFE is for data privacy.