An immediately-invoked function expression (IIFE) is a design pattern that produces a lexical scope using function scoping. IIFE can be used to avoid variable hoisting from within blocks or to prevent us from polluting the global scope, for example:
let bar = 0; // global
(function() {
let foo: number = 0; // In scope of this function
bar = 1; // Access global scope
console.log(bar); // 1
console.log(foo); // 0
})();
console.log(bar); // 1
console.log(foo); // Error
In the preceding example, we have wrapped the declaration of a variable (foo) with an IIFE. The foo variable is scoped to the IIFE function and is not available in the global scope, which explains the error when trying to access it on the last line.
The bar variable is global. Therefore, it can be accessed from within and from outside the IIFE function.
We can also pass a variable...