Module 26 : Javascript immediately Invoked Function
Expressions (IIFE).
🧠 Concept Overview
🔷 What is an IIFE?
IIFE stands for Immediately Invoked Function Expression. It's a JavaScript function that runs as soon as it is defined.
It has two main parts:
Function Expression: Defined using function syntax but wrapped in parentheses.
Invocation: Called immediately using another pair of parentheses.
✅ Syntax of IIFE
javascript code
(function() { // code here runs immediately })();
Or using arrow functions:
javascript code
(() => { // code here runs immediately })();
📌 Why Wrap in Parentheses?
JavaScript distinguishes between:
Function declarations, which must be named.
Function expressions, which can be anonymous and invoked immediately.
By wrapping the function in (), we make JavaScript treat it as an expression, not a declaration.
javascript code
function() {} // ❌ SyntaxError: Function statements require a name (function() {})(); // ✅ Valid IIFE
Example 1: Simple IIFE
javascript
code
(function() { console.log("IIFE ran!"); })();
Output:
nginx
code
IIFE ran!
Example 2: With Variables
javascript code
(function() { let message = "Hello from IIFE!"; console.log(message); })();
javascript code
console.log(message); // ❌ ReferenceError: message is not defined
🔍 Explanation:
The variable message is scoped only inside the IIFE.
It protects the global namespace.
Example 3: IIFE with Parameters
javascript
code
(function(name) { console.log(`Welcome, ${name}`); })("Syeeda");
Output:
code
Welcome, Syeeda
IIFE for Scope Isolation
Problem without IIFE:
javascript code
for (var i = 0; i < 3; i++) { setTimeout(function() { console.log(i); }, 1000); }
Output after 1 second:
code
3
3
3
Fix with IIFE:
javascript code
for (var i = 0; i < 3; i++) { (function(index) { setTimeout(function() { console.log(index); }, 1000); })(i); }
Correct Output:
Copy code
0
1
2
📘 Explanation:
Each loop iteration passes i as a parameter to an IIFE, creating a new scope.
IIFE and the Module Pattern
IIFEs were commonly used to create modular code before import/export became standard.
Example:
javascript
code
const CounterModule = (function() { let count = 0; return { increment: function() { count++; console.log(count); }, reset: function() { count = 0; console.log("Reset done"); } }; })(); CounterModule.increment(); // 1 CounterModule.increment(); // 2 CounterModule.reset(); // Reset done
📘 Explanation:
count is private.
Only the methods returned can access it.
🧠 Dive : Why Use IIFE?
Use Case
Benefit
Avoid polluting global scope
Variables stay private
Create closures in loops
Correct values are captured
One-time initialization
Runs setup code instantly
Module pattern
Encapsulates logic & exposes only public API
📊 Modern JavaScript and IIFE
ES6 Modules have reduced the use of IIFEs.
However, IIFEs are still useful in:
Script files in browsers
Legacy environments
Anonymous async functions
Example: Async IIFE
javascript code
(async () => { const data = await fetch("https://api.example.com/data"); const json = await data.json(); console.log(json); })();
Exercises (With Solutions)
✅ Exercise 1: Write an IIFE that logs "Welcome to JavaScript"
javascript code
// Write here
<details> <summary>✅ Solution</summary>
javascript code
(function() { console.log("Welcome to JavaScript"); })();
</details>
✅ Exercise 2: Create a private counter using IIFE
javascript code
// Expected methods: increase(), decrease(), reset()
<details> <summary>✅ Solution</summary>
javascript code
const counter = (function() { let count = 0; return { increase: function() { count++; console.log(count); }, decrease: function() { count--; console.log(count); }, reset: function() { count = 0; console.log("Reset to 0"); } }; })(); counter.increase(); // 1 counter.increase(); // 2 counter.decrease(); // 1 counter.reset(); // Reset to 0
</details>
🧑🏫 Instructor Tips
Suggested Flow:
Start with problem: Show how global variables can conflict.
Introduce IIFE with syntax and scenarios.
Live code demo using loop with setTimeout.
Discuss module patterns for encapsulation.
Hands-on exercises with breakout rooms or pair programming.
Introduce async IIFEs as modern use.
📚 search
Douglas Crockford popularized IIFEs in early JavaScript module patterns.
The Revealing Module Pattern evolved from IIFEs to build encapsulated components.
IIFEs help mitigate global scope limitations in non-module environments.
Still widely used in browsers, Greasemonkey scripts, Node.js scripts pre-ES6.
Summary
An IIFE is a function that runs as soon as it is defined.
Useful for:
Private variables
Initialization
Creating modules
Avoiding scope pollution
Though ES6 modules reduce their use, IIFEs still have strong relevance in many contexts.
No comments:
Post a Comment