JavaScript IIFE and Interview Classic: setTimeout + var Trap

💡 JavaScript IIFE (Immediately Invoked Function Expression) and Interview Classic: The setTimeout + var Trap Ever seen this weird-looking function? 👇 (function() { console.log("Hello World"); })(); 🤔 Looks different, right? 🧠 What is an IIFE? 👉 An IIFE (Immediately Invoked Function Expression) is a function that: ✔️ Is defined ✔️ And executed immediately No need to call it separately! 🔍 How does it work? (function(name) { console.log("Hello " + name); })("Javascript"); 👉 Output: Hello Javascript 🚀 Why do we use IIFE? 🔒 1. Creates a private scope Variables inside it cannot be accessed outside (function() { var secret = "hidden"; })(); ❌ secret is not accessible outside 🌍 2. Avoids global scope pollution Keeps your code clean and prevents conflicts. ⚡ 3. Helps with closures (classic interview use-case) This is one of the most famous questions asked in interviews 👇 for (var i = 0; i < 5; i++) { setTimeout(() => { console.log(i); }, 1000); } 🤔 What will be the output? 👉 Most people expect: 0 1 2 3 4 ❌ But the actual output is: 5 5 5 5 5 🧠 What’s happening here? 🔹 var is function-scoped, not block-scoped 🔹 The loop finishes execution first → i becomes 5 🔹 setTimeout runs later (asynchronously) 🔹 All callbacks share the same reference of i 👉 So every console.log prints 5 ✅ How to fix it? 🔹a) Using let (block scope): for (let i = 0; i < 5; i++) { setTimeout(() => { console.log(i); }, 1000); } ✔️ Output: 0 1 2 3 4 🔹b) Using Closure (if you must use var): for (var i = 0; i < 5; i++) { (function(i) { setTimeout(() => { console.log(i); }, 1000); })(i); } What is this (function(i) { ... })(i)? 👉 This is an Immediately Invoked Function Expression (IIFE) (It runs immediately after being defined) So for each loop iteration: 🔹A new function is created 🔹It gets its own copy of i as a parameter 👉How closure helps here Inside the loop: First iteration → i = 0 → function runs with i = 0 → setTimeout remembers this i Second iteration → i = 1 → new function with i = 1 → new closure created 👉 This happens for all iterations So instead of sharing one i, we now have 5 different i values stored separately Final result After 1 second: 0 1 2 3 4 ✅ Each setTimeout prints its own preserved value 🔥 Simple analogy Think of it like: ❌ Without closure → 5 people sharing one notebook ✅ With closure → each person gets their own notebook 🚀 Key takeaway 👉 Closures allow functions to remember the variables from their scope 👉 IIFE creates a new scope for each iteration 👉 That’s why this fixes the var problem #JavaScript #CodingInterview #FrontendDevelopment #WebDevelopment #LearnInPublic

To view or add a comment, sign in

Explore content categories