Node.js exports vs module.exports: Key differences explained

🔥 Node.js Developers: Do you really understand exports vs module.exports? This confusion trips up even experienced developers. Let me clear it up once and for all 👇 When you run this code: console.log(module.exports === exports); // true They're equal! So what's the difference? Here's the key: At the start of every module, Node.js does this: const module = { exports: {} }; const exports = module.exports; exports is just a reference (shorthand) pointing to the same object as module.exports. Think of it like this JavaScript example: const user = { address: { city: "Mumbai" } }; let address = user.address; address.pinCode = 400001; console.log(user.address.pinCode); // 400001 When we modify address, user.address changes too because they point to the same memory location. The same applies to exports! ✅ This WORKS: exports.add = (a, b) => a + b; // You're mutating the shared object ✅ This WORKS: module.exports = class User {}; // You're directly replacing what gets exported ❌ This BREAKS: exports = { name: "Sharvil" }; // You broke the reference! // module.exports still points to {} 🎯 The Critical Rule: Only module.exports gets returned when you require() a module. The exports variable is just a convenience. 💡 Best Practice: - Use exports for multiple properties. - Use module.exports for single classes/functions. - Never reassign exports directly. Have you been bitten by this before? Drop a comment with your experience! 📚 Currently learning "Fundamentals of Node.js" as part of Anurag Singh's "Complete Backend with Node.js" course. 🙌 Thanks Anurag Singh for explaining core concepts so clearly. #NodeJS #JavaScript #WebDevelopment #Programming #CodingTips #BackendDevelopment #CommonJS

To view or add a comment, sign in

Explore content categories