IIFE
Immediately Invoked Function Expression
An IIFE is a javascript function that runs as soon as it is defined.
(function () { statements})();
- First grouping () is anonymous function which prevents accessing variables and pollutting the global scrope.
- Second part creates the immediately invoked function express, which the js engine will directly interpret the function
(function () { var aName = "Barry";})();// Variable aName is not accessible from the outside scopeaName // throws "Uncaught ReferenceError: aName is not defined"
Assigning IIFE to a variable stores the functions's return value.
var result = (function () { var name = "Barry"; return name; })(); // Immediately creates the output: result; // "Barry"