HomeJAVASCRIPTWhat are modules in JavaScript?

What are modules in JavaScript?

In JavaScript, modules are reusable pieces of code that are stored in separate files and can be imported or exported when needed. They help in organizing code, making it more maintainable, scalable, and easier to debug.

🔹 Why Modules?

Before modules, everything was written in one large file or using global variables, which caused naming conflicts and poor code organization. Modules solve this problem by keeping code encapsulated.


🔹 Key Concepts of JavaScript Modules

Exporting – You define what part of a module should be shared.

// math.js 
export const add = (a, b) => a + b; 
export const subtract = (a, b) => a - b; // or 
export multiple at once export { add, subtract }; 

You can also have a default export (only one per file):

// logger.js 
export default function log(message) { console.log(message); }

Importing – You use code from another module.

// main.js 
import { add, subtract } from './math.js'; 
import log from './logger.js'; 
console.log(add(5, 3)); // 8 
log("Hello from module!"); // Hello from module!

File Scope – Variables and functions inside a module are not global by default; they are scoped to that module.


🔹 Types of Modules

ES6 Modules (ESM) – The modern standard (import / export).

  • Works in browsers (with <script type="module">) and Node.js (with .mjs or "type": "module" in package.json).

<script type="module" src="main.js"></script>

CommonJS Modules – Used in Node.js before ES6 (require / module.exports).

 // math.cjs 
 module.exports = { add: (a, b) => a + b, }; 
 // main.cjs 
 const { add } = require('./math.cjs'); 
 console.log(add(2, 3)); // 5

🔹 Benefits of Using Modules

  • Avoids global variable pollution.
  • Encourages code reusability.
  • Makes projects more scalable.
  • Helps with lazy loading (import only when needed).
  • Works well with bundlers (Webpack, Rollup, Vite).

👉 In short: Modules in JavaScript are files with their own scope, where you can export and import functionalities across different parts of an application.

Share: 

No comments yet! You be the first to comment.

Leave a Reply

Your email address will not be published. Required fields are marked *