IIFE in JavaScript
IIFE : Immediately Invoked Function Expression
IIFE is termed as Immediately Invoked Function Expression. Sometimes you need to call the function, just after it’s definition. IIFE is the approach which can be very helpful in this case.
- IIFE is used to avoid variable hoisting from within blocks, protect against polluting the global environment
- It simultaneously allow public access to methods while retaining privacy for variables defined within the function.
- IIFE and pronounced as “iffy.”
IIFE are functions that do not have a name as well. They only run once when the interpreter runs into it.
(function() {
var addNumbers = 4 + 4;
return addNumbers;
})();
The set of matching parenthesis after return addNumbers tell the interpreter to immediately run this function. The outermost parenthesis before the function keyword and at the end of the function are grouping operators, telling the interpreter to make this function an expression.
A few helpful reasons to use anonymous functions and IIFE in your code:
- To perform a task for event handlers, listeners, and callbacks — anonymous functions to maintain data privacy .
- To use as an argument when a function is called — anonymous functions & IIFE
- prevent conflicts between script files that could have the same variable names — anonymous functions & IIFE
Important Points:
- IIFE follow their own scope like any other function/variable in JavaScript.
- The part of the name immediately invoked is sometimes confusing to new developers as they expect the IIFE to execute irrespective of function scope, this is wrong.
For example, let us take the following example where the IIFE is defined within a function and will only be immediately invoked if we call the Parent Function.
function myFunction()
{
console.log(“Welcome to”);
(function() { console.log(“JavaScript!”); })();
console.log(“Hi There!”);
}
//Output:
Welcome to
JavaScript!
Hi There!”
- IIFE have there own scope i.e. the variables you declare in the Function Expression will not be available outside the function.
- Similarly to other function IIFE can also be named or anonymous, but even if an IIFE does have a name it is impossible to refer/invoke it.
Advantages of IIFE:
- Do not create unnecessary global variables and functions
- Functions and variables defined in IIFE do not conflict with other functions & variables even if they have same name.
- Organize JavaScript code.
- Make JavaScript code maintainable.