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
Why JavaScript IIFE is a manual module system
More Relevant Posts
-
🚨 JavaScript Gotcha: Objects as Keys?! Take a look at this 👇 const a = {}; const b = { key: 'b' }; const c = { key: 'c' }; a[b] = 123; a[c] = 456; console.log(a[b]); // ❓ 👉 What would you expect? 123 or 456? 💡 Actual Output: 456 🤯 Why does this happen? In JavaScript, object keys are always strings or symbols. So when you use an object as a key: a[b] → a["[object Object]"] a[c] → a["[object Object]"] Both b and c are converted into the same string: "[object Object]" ⚠️ That means: a[b] = 123 sets " [object Object] " → 123 a[c] = 456 overwrites it → 456 So finally: console.log(a[b]); // 456 🧠 Key Takeaways ✅ JavaScript implicitly stringifies object keys ✅ Different objects can collide into the same key ❌ Using objects as keys in plain objects is unsafe 🔥 Pro Tip If you want to use objects as keys, use a Map instead: const map = new Map(); map.set(b, 123); map.set(c, 456); console.log(map.get(b)); // 123 ✅ ✔️ Map preserves object identity ✔️ No unexpected overwrites 💬 Final Thought JavaScript often hides complexity behind simplicity. Understanding these small quirks is what separates a developer from an expert. #JavaScript #WebDevelopment #FrontendDevelopment #Programming #Coding #JavaScriptTips #JSConfusingParts #DevelopersLife #CodeNewbie #LearnToCode #SoftwareEngineering #TechTips #CodeQuality #CleanCode #100DaysOfCode #ProgrammingTips #DevCommunity #CodeChallenge #Debugging #JavaScriptDeveloper #MERNStack #FullStackDeveloper #ReactJS #NodeJS #WebDevTips #CodingLife
To view or add a comment, sign in
-
-
Stop writing JavaScript like it’s still 2015. 🛑 The language has evolved significantly, but many developers are still stuck using clunky, outdated patterns that make code harder to read and maintain. If you want to write cleaner, more professional JS today, start doing these 3 things: **1. Embrace Optional Chaining (`?.`)** Stop nesting `if` statements or using long logical `&&` chains to check if a property exists. Use `user?.profile?.name` instead. It’s cleaner, safer, and prevents those dreaded "cannot read property of undefined" errors. **2. Master the Power of Destructuring** Don't repeat yourself. Instead of calling `props.user.name` and `props.user.email` five times, extract them upfront: `const { name, email } = user;`. It makes your code more readable and your intent much clearer. **3. Use Template Literals for Strings** Stop fighting with single quotes and `+` signs. Use backticks (`` ` ``) to inject variables directly into your strings. It handles multi-line strings effortlessly and makes your code look significantly more modern. JavaScript moves fast—make sure your coding habits are moving with it. What’s one JS feature you can’t live without? Let’s chat in the comments! 👇 #JavaScript #WebDevelopment #CodingTips #SoftwareEngineering #Frontend #Programming
To view or add a comment, sign in
-
You add TypeScript to the project. Half the types are any. You basically wrote JavaScript with some extra syntax. TypeScript doesn't make your code safer. You do. And using any turns off the whole tool. Here's what most people miss: any doesn't stay where you put it. It spreads. function getUser(id: string): any { return api.fetch("/users/" + id); } const user = getUser("123"); const name = user.name; const upper = name.toUpperCase(); Every variable in this chain is any. No autocomplete, no safe changes, no errors caught before release. One any at the start shuts down the whole process. This is type erosion. It acts like tech debt — hidden until it causes problems. Before you type any, ask yourself two questions. First question: Do I really not know the type? If the data comes from an API — describe its structure. A partial type is much better than any. Second question: Am I just avoiding a type error? The compiler warns you, and you ignore it. That's not a fix. It's just @ts-ignore with extra steps. Use unknown instead. It means "I don't know" but makes you check before using it. any trusts without question. unknown requires proof. If your code has more than 5% any, you're not really using TypeScript. You're just adding decorations to JavaScript. Run npx type-coverage. Look at the number. Then decide. any is not a type. It's a surrender. #TypeScript #Frontend #JavaScript #WebDev #SoftwareEngineering #CodeQuality
To view or add a comment, sign in
-
-
Small JavaScript bugs keep escaping to production and breaking critical user flows. Debugging inconsistent runtime behavior steals time from feature delivery. ────────────────────────────── Understanding Type Declaration Files (.d.ts) Ever wondered how to make TypeScript work seamlessly with JavaScript libraries? Let's dive into .d.ts files! #typescript #javascript #development #typedeclaration ────────────────────────────── Core Concept Type declaration files, or .d.ts files, are crucial when working with TypeScript and JavaScript libraries. Have you ever faced issues with type safety while using a library? These files help bridge that gap! Key Rules • Always create a .d.ts file for any JavaScript library that lacks TypeScript support. • Use declare module to define the types of the library's exports. • Keep your declarations organized and maintainable for future updates. 💡 Try This declare module 'my-library' { export function myFunction(param: string): number; } ❓ Quick Quiz Q: What is the main purpose of a .d.ts file? A: To provide TypeScript type information for JavaScript libraries. 🔑 Key Takeaway Type declaration files enhance type safety and improve your TypeScript experience with external libraries!
To view or add a comment, sign in
-
JavaScript is easy. Until it isn't. 😅 Every developer has been there. You're confident. Your code looks clean. You hit run. And then: " Cannot read properties of undefined (reading 'map') " The classic JavaScript wall. Here are 7 JavaScript mistakes I see developers make constantly and how to fix them: 1. Not understanding async/await ⚡ → Wrong: | const data = fetch('https://lnkd.in/dMDBzbsK'); console.log(data); // Promise {pending} | → Right: | const data = await fetch('https://lnkd.in/dMDBzbsK'); | 2. Using var instead of let/const → var is function scoped and causes weird bugs → Always use const by default. let when you need to reassign. Never var. 3. == instead of === → 0 == "0" is true in JavaScript 😱 → Always use === for comparisons. Always. 4. Mutating state directly in React → Wrong: user.name = "Shoaib" → Right: setUser({...user, name: "Shoaib"}) 5. Forgetting to handle errors in async functions → Always wrap await calls in try/catch → Silent failures are the hardest bugs to track down 6. Not cleaning up useEffect in React → Memory leaks are real → Always return a cleanup function when subscribing to events 7. Treating arrays and objects as primitives → [] === [] is false in JavaScript → Reference types don't compare like numbers — learn this early JavaScript rewards the developers who understand its quirks. 💡 Which of these caught YOU off guard when you first learned it? 👇 #JavaScript #WebDevelopment #Frontend #FullStackDeveloper #React #Programming #CodingTips #Developer #Tech #Pakistan #LearnToCode #JS #SoftwareEngineering #100DaysOfCode #PakistaniDeveloper
To view or add a comment, sign in
-
-
🔥 var vs let vs const in JavaScript (Explained Simply) Understanding the difference between `var`, `let`, and `const` is essential for writing clean and bug-free JavaScript code. Let’s break it down 👇 🔹 1️⃣ var #Example var name = "Amit"; var name = "Rahul"; // Re-declaration allowed ✅ Function scoped ✅ Can be re-declared and updated ⚠️ Hoisted with `undefined` ❌ Can cause unexpected bugs 👉 Avoid using `var` in modern JavaScript. 🔹 2️⃣ let #Example let age = 25; age = 30; // Update allowed ✅ Block scoped ❌ Cannot be re-declared in same scope ✅ Can be updated ✅ Safer than `var` 👉 Use `let` when the value needs to change. 🔹 3️⃣ const #Example const pi = 3.14; // pi = 3.1415; ❌ Error ✅ Block scoped ❌ Cannot be re-declared ❌ Cannot be updated ✅ Must initialize at declaration 💡 For objects/arrays → You can modify properties, but not reassign the reference. 🚀 Best Practice ✔️ Use `const` by default ✔️ Use `let` when reassignment is required ❌ Avoid `var` Writing cleaner code starts with choosing the right variable declaration. #JavaScript #WebDevelopment #Frontend #Programming #CodingTips #Developers
To view or add a comment, sign in
-
-
🧠 𝗪𝗿𝗶𝘁𝗶𝗻𝗴 𝗰𝗹𝗲𝗮𝗻𝗲𝗿, 𝘀𝗺𝗮𝗿𝘁𝗲𝗿 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝘄𝗶𝘁𝗵 𝗗𝗲𝘀𝘁𝗿𝘂𝗰𝘁𝘂𝗿𝗶𝗻𝗴 Destructuring is one of those features in JavaScript that can significantly improve code readability and enhances Developers Experience—yet it’s often underutilized or misunderstood. So I decided to break it down in a structured way. New Blog Published: “Mastering Destructuring in JavaScript” https://lnkd.in/gHAWq_sP 🔍 What’s covered in the blog: 🔹 Array & object destructuring fundamentals 🔹 Nested destructuring patterns 🔹 Default values cases 🔹 Practical use cases for writing cleaner, maintainable code Hitesh Choudhary Piyush Garg Akash Kadlag Suraj Kumar Jha Chai Aur Code Nikhil Rathore Jay Kadlag DEV Community #JavaScript #WebDevelopment #TechnicalWriting #CleanCode #LearningInPublic #Chaicode #Cohort
To view or add a comment, sign in
-
Small JavaScript bugs keep escaping to production and breaking critical user flows. Debugging inconsistent runtime behavior steals time from feature delivery. ────────────────────────────── Unpacking Array.find() and findIndex() in JavaScript Let’s dive into two handy array methods in JavaScript: find() and findIndex(). #javascript #arrays #codingtips ────────────────────────────── Core Concept Have you ever needed to locate an item in an array? The methods find() and findIndex() are perfect for that! They allow us to search through an array based on a condition. Which one do you think is more useful? Key Rules • Array.find() returns the first matching element in an array. • Array.findIndex() returns the index of the first matching element. • Both methods take a callback function as an argument to determine the match. 💡 Try This const numbers = [1, 2, 3, 4, 5]; const found = numbers.find(num => num > 3); const index = numbers.findIndex(num => num > 3); ❓ Quick Quiz Q: What does find() return if no match is found? A: It returns undefined. 🔑 Key Takeaway Knowing when to use find() versus findIndex() can streamline your code and enhance readability.
To view or add a comment, sign in
-
Small JavaScript bugs keep escaping to production and breaking critical user flows. Debugging inconsistent runtime behavior steals time from feature delivery. ────────────────────────────── Getting Started with ES Modules: Import and Export Curious about ES Modules in JavaScript? Let's dive into the basics of import and export! #javascript #esmodules #webdevelopment #coding ────────────────────────────── Core Concept Have you ever wondered how to better organize your JavaScript code? ES Modules are a great way to achieve that! They allow you to break your code into reusable pieces and manage dependencies more effectively. Key Rules • Use export to expose functions, objects, or values from a module. • Use import to bring those exported features into another module. • Remember to include the file extension for local modules (e.g., .js). 💡 Try This // math.js export function add(a, b) { return a + b; } // main.js import { add } from './math.js'; console.log(add(2, 3)); // Outputs: 5 ❓ Quick Quiz Q: What keyword do you use to bring in functionalities from another module? A: import 🔑 Key Takeaway Start using ES Modules today to improve your code organization and maintainability!
To view or add a comment, sign in
-
Why I don't chain everything in JavaScript anymore Method chaining in JavaScript looks elegant at first glance. But over time, I realized it often comes with hidden costs. Long chains can: • Reduce readability • Hide unnecessary computations • Make debugging harder When everything happens in a single line, understanding what exactly went wrong becomes a challenge. Instead, I started breaking logic into small, named steps: // ❌ Harder to read & debug const result = users .filter(u => u.active) .map(u => u.profile) .filter(p => p.age > 18) .sort((a, b) => a.age - b.age); // ✅ Easier to read & maintain const activeUsers = users.filter(u => u.active); const profiles = activeUsers.map(u => u.profile); const adults = profiles.filter(p => p.age > 18); const result = adults.sort((a, b) => a.age - b.age); A simple rule I follow now: • 1–2 chain steps → 👍 totally fine • 3–4 steps → 🤔 think twice • 5+ steps → 🚩 break it down Cleaner code isn’t about writing less — it’s about making it easier to understand. What’s your take on method chaining? #javascript #webdevelopment #cleancode #frontend #programming
To view or add a comment, sign in
-
Explore related topics
- How Developers Use Composition in Programming
- Intuitive Coding Strategies for Developers
- How to Achieve Clean Code Structure
- Code Planning Tips for Entry-Level Developers
- How to Add Code Cleanup to Development Workflow
- How to Write Clean, Error-Free Code
- How to Improve Code Maintainability and Avoid Spaghetti Code
- Principles of Elegant Code for Developers
- How to Refactor Code Thoroughly
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