Building Your Learning Module...
Getting things ready for you!
Find videos you like?
Save to resource drawer for future reference!
IIFE stands for "Immediately Invoked Function Expression". It's a function that runs as soon as it's defined. Think of it like a function that calls itself automatically!
Wrap the function in parentheses and add () to invoke it immediately!
// Method 1: Recommended
(function() {
console.log('I run immediately!');
})();
// Method 2: Alternative
(function() {
console.log('This also works!');
}());
// Both do the same thing!
// Output: I run immediately!
// Output: This also works!See the difference between normal functions and IIFEs
Variables inside an IIFE are private - they don't pollute the global scope and can't be accessed from outside!
var name = 'Alice'; var age = 25; console.log(name); // Alice console.log(age); // 25 // Global scope polluted! // Anyone can access these ❌
(function() {
var name = 'Alice';
var age = 25;
console.log(name); // Alice
console.log(age); // 25
})();
// Try to access outside:
console.log(name); // undefined
console.log(age); // undefined
// Private! ✅Variables stay private inside the IIFE
You can pass arguments to IIFEs just like regular functions!
// IIFE with parameters
(function(name, age) {
console.log('Name: ' + name);
console.log('Age: ' + age);
})('Alice', 25);
// Output:
// Name: Alice
// Age: 25
// Pass any data you need!Pass configuration objects to IIFEs
IIFEs can return objects with methods - this is the classic Module Pattern!
var counter = (function() {
var count = 0; // Private!
return {
increment: function() {
count++;
return count;
},
decrement: function() {
count--;
return count;
},
getCount: function() {
return count;
}
};
})();
console.log(counter.increment()); // 1
console.log(counter.increment()); // 2
console.log(counter.getCount()); // 2
console.log(counter.decrement()); // 1
// Can't access count directly!
console.log(counter.count); // undefinedCreate a calculator with private state using IIFE
You can use arrow functions for shorter IIFE syntax!
// Traditional IIFE
(function() {
console.log('Old style');
})();
// Arrow function IIFE
(() => {
console.log('Modern style');
})();
// With parameters
((name) => {
console.log('Hello, ' + name);
})('Alice');
// Output:
// Old style
// Modern style
// Hello, AliceUse async/await inside an IIFE
(function() {
var temp = 'temporary';
// Use temp here
})();
// temp doesn't exist outsidevar module = (function() {
var private = 'secret';
return {
public: 'exposed'
};
})();(function() {
// Setup code
console.log('App initialized');
// Runs immediately!
})();(async () => {
await fetchData();
console.log('Done!');
})();