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
Nidhi Jagga’s Post
More Relevant Posts
-
🧠 Hoisting in JavaScript – Concept Made Simple ⚡ Hoisting is one of those JavaScript concepts that feels confusing at first but becomes very logical once you understand what happens behind the scenes. JavaScript executes code in two phases: 1️⃣ Memory Creation Phase 2️⃣ Execution Phase Hoisting happens in the memory creation phase 👇 🟡 var Hoisting ✔ Declaration is hoisted ✔ Memory is allocated ✔ Value is set to undefined This is why variables declared with var can be accessed before their declaration — but their value isn’t available yet. ⚠️ This behavior often leads to unexpected bugs, which is why var is generally avoided today. 🔵 let & const Hoisting ✔ Declaration is hoisted ❌ NOT initialized in memory They exist in something called the Temporal Dead Zone (TDZ) 🛑 Accessing them before declaration results in an error. 👉 This makes let and const more secure and predictable than var. 🟢 Function Hoisting ✔ Function declarations are fully hoisted ✔ Stored completely in memory during creation phase This allows functions to be used before they appear in the code, making execution smoother. ⚠️ This applies only to function declarations, not function expressions. 🎯 Key Takeaways ✅ Hoisting is about memory allocation, not moving code ✅ var is hoisted with undefined ✅ let and const are hoisted but locked in TDZ ✅ Functions are fully available during execution Understanding hoisting = strong JavaScript foundation 💪 💡 Master the basics, and advanced JavaScript becomes easy 🔁 Share this with someone learning JS 📌 Save it for quick revision before interviews #JavaScript #Hoisting #JSConcepts #WebDevelopment #FrontendDeveloper #Programming #CodingBasics #LearnJavaScript 🚀
To view or add a comment, sign in
-
-
🚀 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗮𝘀𝘆𝗻𝗰/𝗮𝘄𝗮𝗶𝘁: 𝘄𝗵𝘆 𝗶𝘁 𝗹𝗼𝗼𝗸𝘀 𝘀𝘆𝗻𝗰𝗵𝗿𝗼𝗻𝗼𝘂𝘀 𝗯𝘂𝘁 𝗶𝘀𝗻’𝘁 JavaScript doesn’t execute async/await synchronously; it only makes asynchronous code easier to read. Example: console.log("A"); async function test() { console.log("B"); await Promise.resolve("C"); console.log("D"); } test(); console.log("E"); Output: A B E D What actually happens: 1) Global execution starts "A" is printed 2) test() is called "B" is printed 3) await Promise.resolve("C") • The promise is already resolved, but await still pauses, 𝗮𝘄𝗮𝗶𝘁 𝗻𝗲𝘃𝗲𝗿 𝗰𝗼𝗻𝘁𝗶𝗻𝘂𝗲𝘀 𝗶𝗺𝗺𝗲𝗱𝗶𝗮𝘁𝗲𝗹𝘆 • Suspends test execution and lets the rest of the code run first • The remaining code (console.log("D")) is scheduled as a microtask 4) Global code continues "E" is printed 5) Microtask queue runs async function resumes from where it paused "D" is printed See? Nothing got blocked. That’s JavaScript for you, and async/await just keeps async code readable. Thanks to Akshay Saini 🚀 for explaining this concept in Namaste Javascript, which made async/await click for me! 👏👏 #JavaScript #AsyncAwait #EventLoop #FrontendDevelopment #WebDevelopment
To view or add a comment, sign in
-
Ever wondered how JavaScript handles asynchronous code while being single-threaded? Here’s a visual breakdown using setTimeout() 👇 🔄 Execution Flow Explained 1️⃣ Global Execution (Main Function) When the program starts, the main function (global execution context) is pushed into the Call Stack. All synchronous code runs first. 2️⃣ Encountering an Async Function When JavaScript encounters an asynchronous function like setTimeout, it: Pushes it into the Call Stack Immediately removes (pops) it after registering the task 3️⃣ Web API Takes Control The async task is handed over to the Web API, where: The timer starts running (e.g., 4 seconds) JavaScript does NOT wait — it continues executing other code 4️⃣ Callback Queue Once the timer completes: The callback function (console.log("Hello World")) is pushed into the Callback Queue 5️⃣ Event Loop in Action The Event Loop continuously checks: Is the Call Stack empty? 6️⃣ Execution When the Call Stack becomes empty: The Event Loop moves the callback from the Callback Queue to the Call Stack The callback executes and prints the output 🎉 JavaScript is single-threaded, but thanks to: Web APIs Callback Queue Event Loop …it can handle non-blocking asynchronous operations efficiently. If you have any doubts or want to discuss this further, feel free to connect with me or drop a comment. Happy to help! Apoorv M. #JavaScript #EventLoop #WebAPI #AsynchronousJavaScript #Frontend #WebDevelopment #Programming #LearnJavaScript
To view or add a comment, sign in
-
-
Understanding why Promise.all() needs an array in JavaScript Many developers try this and get confused 👇 ❌ Wrong way Promise.all(p1, p2); ✅ Correct way Promise.all([p1, p2]); 🤔 Why does this happen? Promise.all() accepts only ONE argument, and that argument must be an iterable (most commonly an array). 👉 An array allows JavaScript to loop through multiple promises and wait for all of them to resolve. ✅ Working example let p1 = new Promise((resolve) => { resolve(1); }); let p2 = new Promise((resolve) => { resolve(2); }); Promise.all([p1, p2]) .then((data) => { console.log(data); // [1, 2] }); ❌ Why `Promise.all(p1, p2)` throws an error? When you write: Promise.all(p1, p2); JavaScript treats it as: Promise.all(p1); But p1 is a "Promise object", not an iterable like an array. So JS throws: TypeError: object is not iterable 🧠 Easy way to remember > Promise.all waits for a collection of promises, not individual ones Always wrap promises inside an array. ⚠️ One more important thing If any promise rejects, Promise.all() immediately rejects. Promise.all([Promise.resolve(1), Promise.reject("Error")]) .catch(console.error); // Error 💡 Hope this helps someone avoid a common JavaScript pitfall! . . . . . #SRYTAL #JavaScript #Promises #WebDevelopment #Frontend #Learning #Promise.all #Growtogether
To view or add a comment, sign in
-
🧠 “JavaScript is Single-Threaded” What Does That ACTUALLY Mean? You’ve probably heard this line many times: JavaScript is single-threaded But what does it really mean? And why is it actually a good thing? Let’s break it down simply 👇 -- What is a “thread”? A thread means a path of execution. - Single-threaded 👉 does one task at a time - Multi-threaded 👉 can do multiple tasks at the same time -- JavaScript is single-threaded means… - JavaScript has ONE call stack - It can run ONE piece of code at a time Example: console.log("A"); console.log("B"); console.log("C"); Output will always be: A B C - No skipping. No parallel run. - Everything runs line by line. - Real-life analogy 🚶♂️ Think of one cashier at a shop: - One customer is handled at a time - Others wait in a queue - No confusion - No mixed payments 💸 That cashier = JavaScript thread - But wait… JavaScript feels fast 🤔 Yes! Because of: ✅ Event Loop ✅ Callbacks / Promises ✅ Async / Await Long tasks (API calls, timers, file reading): - Are sent outside - JavaScript continues working - Result comes back later So JavaScript is: - Single-threaded but non-blocking -- Why NOT double-threaded? Multi-threading causes: - Race conditions ❌ - Deadlocks ❌ - Complex debugging ❌ JavaScript avoids this by: - Keeping execution simple - Making code predictable - Reducing bugs Simple > Complex -- One-line summary 💡 JavaScript runs one thing at a time, but smartly handles waiting tasks in the background If this made “single-threaded” clear, give it a 👍 Many developers fear this term but it’s actually JavaScript’s strength 💛 #JavaScript #Single_Threaded #Beginners #QA #Learning
To view or add a comment, sign in
-
-
I was working on a project that was built using JavaScript. Everything was going fine at first. But when the project reached its final stage and I started using JavaScript more heavily—pushing it closer to its limits—problems began to appear. At this stage, the application gradually became laggy and started hanging over time, especially when machine-level or low-level heavy processing was required. I tried various optimization techniques and did a lot of research, but I didn’t get any significant performance improvement. That’s when I realized the issue wasn’t just with the code—it was actually a language-level limitation. One of the biggest reasons is that JavaScript is fundamentally single-threaded. This model works very well for I/O-bound and event-driven applications, but when it comes to CPU-intensive tasks, it becomes a bottleneck for the system. While working on this project, I saw firsthand that even a short block on the main thread could slow down the entire system, freeze the UI, and ruin overall responsiveness. Although JavaScript provides abstractions like async/await, promises, and even worker threads, they still can’t fully overcome the core limitation of the main execution thread. When you try to perform low-level or machine-oriented tasks using JavaScript, the runtime cannot effectively utilize multiple CPU cores. From this experience, I clearly understood that for building low-level, high-performance systems, languages like Rust or C++ are far more suitable. These languages offer true multithreading, fine-grained memory control, and predictable performance—qualities that are critical for system-level work. JavaScript is undoubtedly a very powerful language and works excellently in many areas, especially for web and I/O-heavy applications. But after working on this project, I’ve seen its limitations with my own eyes—JavaScript is not a solution for every problem. Choosing the right tool for the right problem is what matters most. #javascript #engineering #coding
To view or add a comment, sign in
-
Why JavaScript’s 'this' causes bugs — and how lexical scope saves you In JavaScript, variables and this follow different rules. Mixing them up is a common source of production bugs. const name = "Global"; const obj = { name: "Object", show() { console.log(name); // lexical scope console.log(this.name); // this context } }; obj.show(); const fn = obj.show; fn(); Output: --------- Global Object Global undefined name uses lexical scope --> decided by where the code is written this.name uses dynamic context --> decided by how the function is called Real production issue This often breaks code in: setTimeout / setInterval Event handlers Callbacks passed to libraries That’s why modern JavaScript prefers: Pure functions,Closures,Arrow functions Simple rule Variables use lexical scope 'this' depends on how a function is called. #javascript #webdevelopment #frontend #cleanCode #lexicalScope #thisKeyword
To view or add a comment, sign in
-
One line of JavaScript. A dozen questions. const isEmpty = obj => !Object.keys(obj).length; It looks clean. It looks useful. But is it production-ready? Here is what this tiny helper doesn’t tell you: The Crash Test: What happens when obj is null or undefined? (Runtime errors). The Array Trap: What if someone passes an array? It might "work," but is that the intended behavior? The Clarity Factor: Is the logic obvious enough for a teammate reviewing this during a Friday afternoon push? The real question isn't just "does it work?" - it’s "is it predictable?" Good code isn't just about functionality. It is about being: Defensive: It anticipates bad data before it hits the logic. Clear: The name matches the behavior exactly. Consistent: It doesn't leave surprises for the next person who touches it. Would you ship this as-is? Or would you add guards, rename it, or avoid the helper entirely to stay closer to standard JS? There are no "right" answers, only different trade-offs. I’m curious to see how you’d handle this. Drop your version in the comments. Because writing code is the easy part. Writing code that a team can trust? That takes deliberate thought. If I were shipping this to a production library,I'd go with something safer: constisEmpty=obj=> obj && obj.constructor===Object&&Object.keys(obj).length===0; Handlesnull/undefined, ensures plain objects only.Longer, but sleeps better at night. What's your version? #JavaScript #WebDevelopment #CleanCode #SoftwareEngineering #Programming Ankit Mehra Kausar Mehra Manoj Kumar (MK) TechRBM PUNKAJJ DAAS Divyajot Angrish Ridhima . Bishesh Dhiman Vikrant Kumar Dhiman Nishant Kumar pardeep singh Kishpinder Kaur Gyanesh Kamal Tarun Lohni
To view or add a comment, sign in
-
Day #2 – How JavaScript Actually Works Behind the Scenes . Many developers say they hate JavaScript. Not because JavaScript is a bad language. But because they write code without understanding how JavaScript executes it internally. . When the internal working is unclear, JavaScript feels confusing and unpredictable. In reality, JavaScript follows very strict and well-defined rules. . To understand this, let’s look at a simple example. . # Reference Image . At the very beginning, the JavaScript engine creates a Global Execution Context. This context represents the global scope of the program. . During the creation phase, memory is allocated. Variables are initialized with undefined ( let, const, var ). Functions are stored as references. No code is executed in this phase. . After memory allocation, the execution phase begins. The engine starts executing the code line by line. . When a is encountered, it is assigned the value 5. When abc(6) is called, a new Function Execution Context is created. . Inside this function context, num receives the value 6. ans is calculated as 12. The value 12 is returned and assigned to value1. Once the function finishes, its execution context is destroyed. . The same process happens again for abc(a). A new function execution context is created. num receives the value 5. ans becomes 10. The value 10 is returned and stored in value2. . Throughout this entire process, JavaScript uses the Call Stack. Every execution context is pushed onto the stack when it starts. When execution is complete, it is popped off. This ensures that JavaScript always knows which code to execute next. . JavaScript is not random. It is not magical. It is deterministic and rule-based. . When developers understand execution context and the call stack, JavaScript stops feeling confusing and starts feeling logical.
To view or add a comment, sign in
-
Explore related topics
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development