JavaScript Self-Invoked Functions (IIFEs)
What is a self-invoked function? (IIFE)
A self-invoked function, also called an Immediately Invoked Function Expression (IIFE) is a Javascript function expression that is invoked immediately after its declaration. A self-invoked function can be a valuable tool for creating isolated scopes and managing variable privacy in javascript applications.
Key aspects of IIFEs:
- IIFEs execute immediately when defined
- Allows creation of private scopes without polluting global namespace
- Return values can be assigned to variables
- Parameters can be passed to IIFEs
Basic syntax:
(function() {
// code here
})();
// OR arrow functions (ES6+)
(() => {
// code here
})();
Why are IIFEs Necessary?
Immediate Execution with Parameters
// Immediately logs provided data
(function(date, location) {
console.log(`Date: ${date.toDateString()}`);
console.log(`Location: ${location}`);
})(new Date(), 'Seattle');
// Immediately logs:
// Date: Thu Oct 16 2025
// Location: Seattle
Avoiding Global Namespace Pollution
// if multiple scripts use the same variable names
// they won't conflict
(function() {
const restaurant = "Dairy Queen";
console.log(user); // "Dairy Queen"
})();
(function() {
const restaurant = "Burger King";
console.log(user); // "Burger King"
})();
Data Privacy/Encapsulation
// Problem: counter value is vulnerable.
var counter = 0;
function increment() {
return ++counter;
}
// FIX: keeps variables private. counterModule isn't directly accessible
const counterModule = (function() {
let count = 0;
return {
increment: function() {
return ++count;
},
decrement: function() {
return --count;
},
getCount: function() {
return count;
}
};
})();
counterModule.count = 100; // WONT WORK!!
// count is not accessible directly
console.log(counterModule.getCount()); // 0
counterModule.increment();
console.log(counterModule.getCount()); // 1
// OUPTUT: 0 1
Module Pattern Implementation
const User = (function() {
let memory = 0;
function add(a, b) {
return a + b;
}
function store(value) {
memory = value;
}
function recall() {
return memory;
}
// Only expose public methods
return {
add: add,
store: store,
recall: recall
};
})();
console.log(Calculator.add(5, 3)); // 8
Calculator.store(10);
console.log(Calculator.recall()); // 10
// memory is private and inaccessible