Nidhi Jagga’s Post

The "One-Hit Wonder" of JavaScript: Why developers still use the IIFE. 🚀 What is an IIFE? An 𝐈𝐈𝐅𝐄 (Immediately Invoked Function Expression) is a JavaScript function that runs as soon as it is defined. Unlike a normal function that you define first and call later, an IIFE executes automatically the moment the JavaScript engine reads it. Most functions wait to be called. The 𝐈𝐈𝐅𝐄 (Immediately Invoked Function Expression) runs the exact moment it is defined. But why would you need a function that runs only once? The answer is 𝐏𝐫𝐢𝐯𝐚𝐜𝐲. 🛡️ Before modern block scoping (`let`/`const`), IIFEs were the standard way to create a private scope. Even today, they are a powerful design pattern for specific scenarios. 𝟒 𝐓𝐞𝐜𝐡𝐧𝐢𝐜𝐚𝐥 𝐔𝐬𝐞 𝐂𝐚𝐬𝐞𝐬 𝐟𝐨𝐫 𝐈𝐈𝐅𝐄𝐬: 1️⃣ 𝐓𝐡𝐞 𝐌𝐨𝐝𝐮𝐥𝐞 𝐏𝐚𝐭𝐭𝐞𝐫𝐧 (𝐄𝐧𝐜𝐚𝐩𝐬𝐮𝐥𝐚𝐭𝐢𝐨𝐧) You can use an IIFE to create "private" variables that cannot be accessed from the outside, while returning only the methods you want to expose (Public API). 2️⃣ 𝐓𝐨𝐩-𝐋𝐞𝐯𝐞𝐥 𝐀𝐬𝐲𝐧𝐜/𝐀𝐰𝐚𝐢𝐭 Before ES Modules allowed top-level await, an 𝐀𝐬𝐲𝐧𝐜 𝐈𝐈𝐅𝐄 was the standard way to run asynchronous setup code immediately: `(async () => { await db.connect(); })();` 3️⃣ 𝐀𝐯𝐨𝐢𝐝𝐢𝐧𝐠 𝐆𝐥𝐨𝐛𝐚𝐥 𝐍𝐚𝐦𝐞𝐬𝐩𝐚𝐜𝐞 𝐏𝐨𝐥𝐥𝐮𝐭𝐢𝐨𝐧 Variables declared inside an IIFE stay inside. They don't leak out and overwrite variables in the global `window` object, preventing bugs in large codebases. 4️⃣ 𝐒𝐚𝐟𝐞 𝐈𝐧𝐢𝐭𝐢𝐚𝐥𝐢𝐳𝐚𝐭𝐢𝐨𝐧 Need to run complex logic just to set a single `const` value? Wrap that logic in an IIFE and return the result. It keeps your code clean and your variables constant. Check out the visual breakdown below! 👇 Do you use Async IIFEs in your projects, or have you moved fully to ES Modules? #JavaScript #WebDevelopment #CodingPatterns #SoftwareEngineering #Frontend #BestPractices

  • graphical user interface

To view or add a comment, sign in

Explore content categories