IMMEDIATELY INVOKED FUNCTION EXPRESSIONS
An anonymous function that is called immediately is most often called an immediately invoked function expression (IIFE). It resembles a function declaration, but because it is enclosed in parentheses it is interpreted as a function expression. This function is then called via the second set of parentheses at the end. The basic syntax is as follows:
(function() {// block code here})();
The use of an IIFE to simulate block scope uses values defined inside a function expression that is executed immediately, thereby offering a block scope–like behavior using function scoped variables. (The utility of the IIFE was much greater in previous versions of ECMAScript 6 where block scoped variables were not supported.) Consider the following example:
// IIFE(function () {for (var i = 0; i < count; i++) {console.log(i);}})();console.log(i); // Throws an error
The preceding code will error when the console.log() outside the IIFE...