25. MEDIUM | Modules in JavaScript
This article will talk about modules in javascript.
JavaScript modules are a way to organize code into separate, reusable files with clear boundaries. They help you write clean, maintainable, and scalable applications.
What is a Module?
A module is simply a file that:
Has its own scope (Module Scope). Variables/Functions defined in the module are not present in global scope.
Can export variables/functions/classes.
Can import things from other modules.
Why Modules?
Without modules:
All code goes into one file 😵
Global variables clash ❌
Hard to maintain
With modules:
Encapsulation ✅
Reusability ✅
Better structure ✅
Types of Modules in JavaScript
1. ES Modules (Modern - Recommended)
Uses import / export
🚢 Exporting
What can be exported?
Variables, Functions & Classes
Two types of exports: -
- Named Export
// person.js file
// In-line individually
export const name = 'shubham';
export const age = 25;
export function greet() {console.log("Hello User!")};
// person.js file
// All at once at the bottom
const name = 'shubham';
const age = 25;
function greet() {console.log("Hello User!")};
export { name, age, greet };
// renaming during export
// export { name, age as userAge, greet as greetUser };
- Default Export
Only one default export per file.
Only functions can be default export.
// math.js file
// In-line individually
export default function sum(a, b) {console.log(a + b)};
// math.js file
// At the bottom
function sum(a, b) {console.log(a + b)};
export default sum;
🚢 Importing
type="module" in the <script> tag or "type": "module" in package.json.// Import named exports from the file person.js
import { name, age } from './person.js';
// renaming during import
// import { name as userName, age } from './person.js';
// Import default export from the file math.js
import sum from './math.js';
// Import everything from the file person.js
import * as something from './person.js';
console.log(something.name); // shubham
console.log(something.age); // 25
console.log(something.greet()); // Hello User!
2. CommonJS (Node.js older way)
Uses require / module.exports
Important Points
Modules are strict mode by default.
Imports are hoisted.
Enables
deferattribute in<script>tag by default.Cannot use
importinside conditions (use dynamic import instead).Circular dependencies can happen (be careful).
Happy reading!

