IIFE (Immediately Invoked Function Expressions)
IIFE (Immediately Invoked Function Expressions) – Why was this needed and why we hardly use it now
IIFE (Immediately Invoked Function Expressions) were a fundamental JavaScript pattern that was frequently used in the past but has become less common today. These were functions that were defined and immediately executed.
They were primarily used to solve variable scoping issues, especially when JavaScript only had global scope available.
(function() {
// Code here
console.log('This is an IIFE!');
})();
Advantages of this method:
(function() {
let user = 'Aram';
console.log(user);
})();
console.log(user); // ReferenceError: user is not defined
Advantages of this method:
IIFEs originally emerged as a solution when JavaScript only had global scope. This meant any variable or function could affect the entire program's behavior. In this context, IIFEs were crucial tools for creating modular approaches and private state.
Maintaining code cleanliness and isolation was important - for example, when importing different libraries that didn't want to modify global variables.
When ES6 introduced let and const operators, and JavaScript gained block scope, IIFE usage declined. These operators automatically limit variables to their code block.
Today we can use `let`, `const`, or even arrow functions without IIFEs, working in a cleaner and simpler way without extra wrapping functions.
let user = 'Aram'; // Block scope
console.log(user);
Advantages of this method:
The popularity of IIFEs was mainly due to JavaScript's limitations when the language lacked block scoping methods.
For example, IIFEs were the best solution to avoid conflicts between different functions and variables.
(function() {
var localVar = 'I am local';
console.log(localVar);
})();
console.log(localVar); // ReferenceError
This method also enabled the creation of functional modules where closures maintained data privacy from external influences.
IIFEs were very important in JavaScript's history, but their usage has declined thanks to ES6 features and new language capabilities. Now we can simply use block scoping and closures, allowing us to write cleaner and simpler code without IIFEs.