JavaScript Tutorial in Hindi #35 | JS Modules (Import/Export)
✅ 1. What are JavaScript Modules?
- Modules are reusable pieces of code (files) that can export variables, functions, or classes.
- Other modules can import these exports to use them.
- Helps organize code into manageable, separate files.
- Supported natively in modern browsers and Node.js.
✅ 2. Why use Modules in JavaScript?
- Encapsulation: Keep code private unless explicitly exported.
- Maintainability: Organize code logically into smaller files.
- Reusability: Share code across multiple files/projects.
- Avoid polluting the global namespace.
✅ 3. Syntax for Exporting and Importing
Exporting
- Named Export: Export multiple items by name.
js
CopyEdit
// utils.js
export function add(a, b) {
return a + b;
}
export const pi = 3.1416;
- Default Export: Export a single main item per file.
js
CopyEdit
// calculator.js
export default function subtract(a, b) {
return a - b;
}
Importing
- Import named exports using curly braces
{}
.
js
CopyEdit
import { add, pi } from './utils.js';
console.log(add(2, 3)); // 5
console.log(pi); // 3.1416
- Import default export without braces, can rename freely.
js
CopyEdit
import subtract from './calculator.js';
console.log(subtract(5, 3)); // 2
- You can also combine both:
js
CopyEdit
import subtract, { add, pi } from './someModule.js';
✅ 4. Types of Exports
Export TypeDescriptionExample | ||
Named Export | Multiple exports by name | export function foo() {} |
Default Export | Single main export per file | export default class {} |
✅ 5. Example: Real-world Usage
Suppose you have two files:
mathUtils.js
js
CopyEdit
export function multiply(a, b) {
return a * b;
}
export const e = 2.718;
app.js
js
CopyEdit
import { multiply, e } from './mathUtils.js';
console.log(multiply(4, 5)); // 20
console.log(e); // 2.718