Hint
Defined and called immediately — creates a private scope
An IIFE is a function that is both defined and invoked immediately. It creates an isolated scope.
// Classic IIFE syntax
(function() {
const private = 'inaccessible outside';
console.log(private);
})();
// Arrow IIFE
(() => {
// isolated scope
})();
// IIFE with parameters
(function(global) {
global.myLib = {};
})(window);
// IIFE returning a value
const result = (() => {
const x = computeExpensiveThing();
return x * 2;
})();
Use cases:
let closure fix)