It is a JavaScript function that runs as soon as it defined. An IIFE (Immediately Invoked Function Expression) can be used for avoiding the variable hoisting from within the blocks. It allows the public access to methods while retaining the privacy for variables defined in the function.
IIFE is a design pattern that is also known as the Self-Executing Anonymous Function. It contains two major parts:
(function () { statements })(); // Syntax of IIFE with ES6 arrow functions (though parentheses only allowed on outside) (() => { /* ... */ })();
Let us try to understand the concept of IIFE by using the following example.
(function() { console.log("Hello World"); })();
We can convert the regular functions into IIFE by using the following steps:
Let's see the illustration for the same in the following example:
// Regular Function. function hello() { console.log("Regular function"); }; // Regular Function execution. hello(); // IIFE creation and execution. (function() { console.log("Immediately Invoked Function Expression"); })();
(function (x, y, z) { console.log(x); console.log(y); console.log(z); })(100, 200, 300);