🔥 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
Node.js exports vs module.exports: Key differences explained
More Relevant Posts
-
🚀 New Blog Published: Node.js Internals Explained While learning backend development through the cohort by Hitesh Choudhary, I started exploring how Node.js actually works internally. A detailed explanation by Piyush Garg about the Node.js internals really helped me understand how things work behind the scenes. So I decided to document my learning in a blog. In this article I explain: • How the V8 Engine executes JavaScript • How libuv enables asynchronous operations • How the Node.js Event Loop works • Node.js internal architecture with diagrams 🔗 Read the full blog here: https://lnkd.in/dhiWGXTC Feedback from the community would be really valuable 🙌 #nodejs #javascript #backenddevelopment #webdevelopment #developers
To view or add a comment, sign in
-
💡React/TypeScript Tip💡 I have seen many React developers struggling to find the exact data type to specify for the event parameter of the event handler when using TypeScript. There is an easy way to find it out. Let's say you want to find out the type of onChange handler event: const handleChange = (event) => { } // JSX <input type='text' onChange={handleChange} /> Then, instead of referring to handleChange directly in the onChange handler, change it to an inline function like this: <input type='text' onChange={(event) => {}} /> Now, If you mouse over the event parameter, you will see the exact type you can use for the event. This works because, when using inline function, the correct type is automatically passed to the function parameter. So with this trick, you will be able to quickly find the type of any of the event parameter without the need of doing a Google search. 𝗙𝗼𝗿 𝗺𝗼𝗿𝗲 𝘀𝘂𝗰𝗵 𝘂𝘀𝗲𝗳𝘂𝗹 𝗰𝗼𝗻𝘁𝗲𝗻𝘁, 𝗱𝗼𝗻'𝘁 𝗳𝗼𝗿𝗴𝗲𝘁 𝘁𝗼 𝗳𝗼𝗹𝗹𝗼𝘄 𝗺𝗲. PS: Last 2 hours left for the Holi special offer to end. Get lifetime access to 𝗣𝗿𝗼/𝗟𝗶𝗳𝗲𝘁𝗶𝗺𝗲 𝗦𝘂𝗯𝘀𝗰𝗿𝗶𝗽𝘁𝗶𝗼𝗻 - ALL My Current + Future Courses/Ebooks/Webinars at just $𝟭𝟮 / ₹𝟭𝟬𝟮𝟬 (instead of regular price $𝟮𝟯𝟲 / ₹𝟮𝟬,𝟬𝟲𝟬) 📚🚀 𝗧𝗵𝗮𝘁'𝘀 𝗮 𝗺𝗮𝘀𝘀𝗶𝘃𝗲 𝟵𝟰% 𝗗𝗶𝘀𝗰𝗼𝘂𝗻𝘁🎉 The offer ends at 12.30 PM IST. Hurry up! 𝘓𝘪𝘯𝘬 𝘪𝘯 𝘵𝘩𝘦 𝘤𝘰𝘮𝘮𝘦𝘯𝘵 𝘢𝘯𝘥 𝘪𝘯 𝘵𝘩𝘦 𝘧𝘦𝘢𝘵𝘶𝘳𝘦𝘥 𝘴𝘦𝘤𝘵𝘪𝘰𝘯 𝘰𝘧 𝘮𝘺 𝘓𝘪𝘯𝘬𝘦𝘥𝘐𝘯 𝘱𝘳𝘰𝘧𝘪𝘭𝘦. #javascript #reactjs #nextjs #typescript #webdevelopment
To view or add a comment, sign in
-
-
🚨 One API Design Mistake I Still See in Many Node.js / JavaScript Projects While reviewing some backend code recently, I noticed a pattern that silently makes APIs harder to maintain and scale. Many developers design APIs like this: POST /getUserData POST /deleteUser POST /updateUserInfo POST /createNewUser At first glance it works… But long term it becomes a maintenance nightmare. Why? ❌ Everything is POST ❌ Endpoint names contain actions ❌ Inconsistent structure ❌ Harder to scale and document ❌ Breaks REST principles This approach turns your API into an action-based system instead of a resource-based system. 💡 A Better Approach (RESTful Design) Design APIs around resources, not actions. Example: GET /users GET /users/123 POST /users PUT /users/123 DELETE /users/123 Now your API becomes: ✅ Predictable ✅ RESTful ✅ Scalable ✅ Easier for frontend teams ✅ Cleaner documentation 🔑 A Rule I Follow in Backend Development Endpoints = Resources HTTP Methods = Actions Resource → /users Action → GET, POST, PUT, DELETE Once you follow this rule, your APIs instantly become cleaner and easier to extend. ⚡ Small API Design Decisions = Huge Long-Term Impact Great backend systems are not just about writing code. They are about designing systems that remain clean even after thousands of requests and hundreds of new features. Curious to know 👇 What is the most common API design mistake you've seen in real projects? Let's discuss in the comments. #javascript #nodejs #backenddevelopment #restapi #webdevelopment #softwareengineering #coding #developers #programming #tech
To view or add a comment, sign in
-
-
💡 Node.js Tip: Handle Async Errors Properly One mistake many developers make in Node.js APIs is not handling async errors correctly. Instead of writing this in every controller: ❌ try/catch everywhere It quickly makes the code messy and hard to maintain. A better approach is to create an async error handler wrapper. Example: const asyncHandler = (fn) => (req, res, next) => Promise.resolve(fn(req, res, next)).catch(next); Now you can write cleaner controllers: const getUsers = asyncHandler(async (req, res) => { const users = await userService.getUsers(); res.json(users); }); ✅ Cleaner controllers ✅ Centralized error handling ✅ Easier debugging Small improvements like this make a big difference in production APIs. How do you handle errors in your Node.js applications? #NodeJS #BackendDevelopment #JavaScript #WebDevelopment #Coding
To view or add a comment, sign in
-
🚀 Node.js Performance Tip (that most devs still miss) If your API feels slow… There’s a high chance you’re doing this 👇 ❌ Sequential API Calls const user = await getUser(); const orders = await getOrders(); const payments = await getPayments(); Each call waits for the previous one. 👉 If each takes 100ms → total = 300ms ✅ Use Promise.all() const [user, orders, payments] = await Promise.all([ getUser(), getOrders(), getPayments() ]); Now they run in parallel. 👉 Total time = ~100ms ⚡ Same logic ⚡ Same code ⚡ But ~3x faster 💡 Rule: If API calls are independent, never run them sequentially. ⚠️ But remember: Only use Promise.all() when requests don’t depend on each other. Small optimization → Huge performance gain 🚀 Comment “More” if you want more backend performance tips 👇 #NodeJS #JavaScript #Backend #WebPerformance #Coding #Developers
To view or add a comment, sign in
-
-
Closures in React: powerful concept, subtle bugs Closures are a fundamental concept in JavaScript. They also explain some of the most confusing bugs that appear in React applications. A closure happens when a function captures variables from the scope where it was created. Those variables remain accessible even after the outer function has finished executing. In React, every render creates a new scope. When a function is defined inside a component, it closes over the values from that specific render. This becomes important when using hooks like useMemo and useCallback. If the dependency array is incomplete, the function may keep referencing outdated values from a previous render. Common situations where this appears: • useCallback capturing an old state value • useMemo computing something with stale props • event handlers referencing outdated variables The result is what developers often call a stale closure. The UI updates, but the function is still working with old data. This is why dependency arrays matter. They are not only about performance. They ensure the function is recreated when its captured values change. A good rule of thumb is simple. If a value is used inside useMemo or useCallback, it usually belongs in the dependency array. I added a small example in the comments showing how a stale closure happens in practice and how to fix it.
To view or add a comment, sign in
-
-
Most developers use require() in Node.js every day, but very few know what actually happens behind the scenes. While exploring the Node.js source code, I found that require() follows a series of internal steps before a module is available in your application. Here’s a simplified breakdown of how it works: Step 1: Resolving the module Node first determines where the module exists. It checks for local files, JSON files, and modules inside the node_modules directory. Step 2: Loading the module Once the correct file is found, Node reads the file content depending on the file type such as .js, .json, or .node. Step 3: Compilation For JavaScript files, Node wraps the module inside an IIFE (Immediately Invoked Function Expression). This creates the familiar function wrapper: (function (exports, require, module, __filename, __dirname) { // module code }); Step 4: Evaluation The wrapped function is executed, and whatever is assigned to module.exports becomes the exported value. Step 5: Caching Finally, the module is cached. If the same module is required again, Node returns the cached version instead of executing it again, which improves performance. Understanding this process helped me better appreciate how Node.js manages modules internally. If you're learning backend development with Node.js, exploring the runtime source code can reveal many interesting insights about how JavaScript actually runs behind the scenes. #NodeJS #JavaScript #BackendDevelopment #WebDevelopment #OpenSource #SoftwareEngineering
To view or add a comment, sign in
-
-
⚠️ A Common React Mistake We Make as React/JS Developers. I have found that one small mistake in React can create very weird UI bugs while working on using Index as Key in a List. Let me explain with an example. Check this code for displaying a list - {items.map((item, index) => ( <div key={index}>{item.name}</div> ))} The above piece of code is something we commonly use. It looks fine, but sometimes it can be dangerous - and we often ignore it. Let me explain why. At first, everything looks fine. No errors. But the real problem starts when the list changes - during insertion or deletion. Imagine the list is: 0 - React 1 - Node 2 - Next Now suppose we delete "React" (index 0). Hence, the new list becomes: 0 - Node 1 - Next But here is the problem. React thinks: Item with key 0 still exists. Item with key 1 still exists. Because the keys (0 and 1) are still there. So instead of understanding: "React was removed" React thinks: "React became Node" "Node became Next" It reuses the old components and just changes the data. Result: Wrong component updates. How can we fix it? Using a stable id as the key. {items.map((item) => ( <div key={item.id}>{item.name}</div> ))} Now imagine: id: 101 - React id: 102 - Node id: 103 - Next We delete React (101). React sees: 101 is gone 102 still exists 103 still exists So, it removes that exact component. Share your thoughts in the comment box. #ReactJS #JavaScript #WebDevelopment #FrontendDevelopment #ReactDeveloper #CodingMistakes #SoftwareDevelopment #LearnToCode #Programming
To view or add a comment, sign in
-
-
🚀JavaScript is single-threaded… yet Node.js handles thousands of concurrent requests. How? JavaScript is single-threaded. So how does Node.js handle thousands of asynchronous operations like file reads, database calls, timers, and network requests without blocking the application? While learning Node.js internals, I tried to break this down with a simple architecture diagram. JavaScript runs inside the V8 engine and executes code line by line using a single call stack. This means only one piece of JavaScript code runs at a time. But when operations like reading a file, making an API request, or starting a timer happen, Node.js doesn't block the main thread waiting for the result. Instead, these operations are delegated to another layer that interacts with the operating system and manages asynchronous tasks. Once the operation finishes, the result is placed in a queue and executed when the call stack becomes free. This is what makes Node.js capable of handling many concurrent operations efficiently. I drew the architecture to understand the flow: JavaScript (Call Stack) → Node.js APIs → Async I/O Layer → Operating System → Event Loop → Callback Execution Two questions for backend developers: 1: What library powers asynchronous I/O and the event loop in Node.js? 2: Which programming languages are used to build the V8 engine, Node.js runtime, and the async I/O layer behind it? Drop your answers in the comments. #NodeJS #JavaScript #BackendDevelopment #AsyncProgramming #EventLoop #WebDevelopment #Libuv #react #mern
To view or add a comment, sign in
-
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