Node.js Modules: require() & ES Import Basics

🔁 Understanding require() & Modules in Node.js When starting with Node.js, one concept that often feels confusing is how modules work. Let’s simplify it 👇 📦 1. require() in Node.js require() is used to import functionality from another file/module. const math = require('./math'); This allows you to reuse code instead of rewriting logic. 🧩 2. Modules Protect Their Scope Every module in Node.js has its own private scope. ✅ Variables & functions inside a module ❌ Are NOT leaked globally This prevents naming conflicts and keeps code maintainable. 📤 3. module.exports (CommonJS – CJS) To share code from a module: module.exports = function add(a, b) { return a + b; }; Then import it using require(). ⚡ 4. ES Modules (Modern Alternative) Instead of: const x = require('module'); We now use: import x from 'module'; ES Modules are cleaner and align with modern JavaScript. 💡 Key Takeaway Modules help you: ✔ Organize code ✔ Avoid global pollution ✔ Build scalable applications #NodeJS #JavaScript #WebDevelopment #Backend #CodingConcepts

To view or add a comment, sign in

Explore content categories