Why JavaScript IIFE is a manual module system

I used to work on a JavaScript codebase where… Every file looked like this 👇Wrapped inside a self-invoking function (IIFE). And honestly…It didn’t make sense to me at first. Why are we doing this? Then I started asking basic questions: 👉 Why do we even split code into multiple files? At a high level → separation of concerns + reusability. We write logic in one file → use it in another.That’s basically what a module system does in any language. Then the next question hit me: 👉 What does IIFE have to do with modules? Here’s the catch: JavaScript initially didn’t have a module system. No imports. No exports. So what happens? 👉 Everything runs in the global scope. Which means: My variables = global Your variables = global Third-party library variables = also global Now imagine same variable names… 💥 Collision. So how did developers deal with this? 👉 Using functions. Because functions in JavaScript create their own scope. So the idea became: Wrap everything inside a function→ invoke it immediately→ expose only what’s needed --> return statement const module = (() => { const p1 = () => {} const p2 = [] const exports = { x1: () => {}, x2: [] } return exports })() Now think about it: 👉 p1 and p2 → private👉 x1 and x2 → public Nothing leaks into global scope. That’s when it clicked for me. This is basically a manual module system. Before:→ CommonJS→ ES Modules Funny thing is… Today we just write: export const x1 = () => {} …but back then, people had to build this behavior themselves. It is not about how things work today but why they exist in the first place. BTW this pattern is called 🫴Revealing Module Pattern.👈 #JavaScript #WebDevelopment #CleanCode #DeveloperJourney #Coding #FrontendDevelopment

To view or add a comment, sign in

Explore content categories