Skip to content

Latest commit

 

History

History
40 lines (27 loc) · 981 Bytes

6. What is IIFE.md

File metadata and controls

40 lines (27 loc) · 981 Bytes

What is IIFE in javascript

An IIFE (Immediately Invoked Function Expression) is a JavaScript function that runs as soon as it is defined.

(function () {
    statements
})();

It is a design pattern which is also known as a Self-Executing Anonymous Function and contains two major parts:

  1. The first is the anonymous function with lexical scope enclosed within the Grouping Operator (). This prevents accessing variables within the IIFE idiom as well as polluting the global scope.

  2. The second part creates the immediately invoked function expression () through which the JavaScript engine will directly interpret the function.

(function () {
    var aName = "Barry";
})();
// Variable aName is not accessible from the outside scope
aName // throws "Uncaught ReferenceError: aName is not defined"
var result = (function () {
    var name = "Barry"; 
    return name; 
})(); 
// Immediately creates the output: 
result; // "Barry"