51. Immediately Invoked Function Expressions (IIFEs)
An IIFE is a function that is executed immediately after it is defined. Before ES6 introduced block scope (let/const), IIFEs were the primary way to create a private scope and prevent variables from polluting the global scope.
Syntax
There are two parts:
- Enclosing the function in parentheses
()to treat it as an expression. - Adding trailing parentheses
()to immediately call the function.
javascript (function() { let tempVariable = 'I am private!'; console.log(tempVariable); })(); // The function runs immediately
// console.log(tempVariable); // ReferenceError: tempVariable is not defined
Modern Use
While let and const have made IIFEs less crucial for simple variable isolation, they are still used in module bundling and when running code that needs to execute precisely once upon load without creating temporary global variables.