Hello readers π, welcome to the 11th blog of this JavaScript series.
In this article, we'll explore JavaScript Modules - a powerful feature that helps us organize our code into smaller, reusable, and manageable pieces.
In real life, you do things like:-
- Keep your books organized by subject (Code Organization)
- Reuse your notes across multiple subjects (Reusability)
- Share your notes with friends (Sharing Code)
In JavaScript, this kind of organization can be done using Modules.
The Problem First β Why Do We Even Need Modules?
Imagine you're building a big project and you write everything in one single file β app.js. As the project grows, that file becomes 500, 1000, 2000+ lines long. Now:
- It's very hard to find a specific function
- Multiple developers can't work on the same file without conflicts
- If something breaks, debugging becomes a nightmare
This is exactly the problem modules solve.
The Global Scope Problem
Without modules, if you have two JavaScript files loaded in HTML:
<script src="file1.js"></script>
<script src="file2.js"></script>
Both files share the same global scope. So if file1.js has:
let userName = "satya";
And file2.js also has:
let userName = "sootar"; // Conflict!
They will conflict with each other, causing bugs that are very hard to track down.
Modules fix this β each module gets its own scope. Variables inside a module are not visible to the outside world unless you explicitly export them.
Definition
A module is a JavaScript file that can:
- Export its values (functions, variables, classes) to share with other files
- Import values from other modules to use them
Two keywords power the entire module system:
| Keyword | Purpose |
|---|---|
export |
Share something from a file |
import |
Use something from another file |
Exporting β Sharing Values from a Module
There are two types of exports in JavaScript.
1. Named Exports
You can export multiple things from a single file. Each export has a specific name.
// math.js
export function add(a, b) {
return a + b;
}
export function subtract(a, b) {
return a - b;
}
export const PI = 3.14159;
You can also declare everything first and export at the bottom:
// math.js
function add(a, b) {
return a + b;
}
function subtract(a, b) {
return a - b;
}
const PI = 3.14159;
export { add, subtract, PI }; // Export all at once
Both approaches work exactly the same way. Use whichever feels cleaner to you.
2. Default Export
Each module can have only one default export. It is used when a module has one main thing to export.
// greet.js
export default function greet(name) {
return `Hello, ${name}!`;
}
Important: A module can only have one default export. Having more than one will throw a
SyntaxError.
Importing β Using Values from Another Module
Once you've exported something, you can import it in any other file.
Importing Named Exports
When importing named exports, you use the exact same name wrapped in curly braces {}.
// main.js
import { add, subtract, PI } from "./math.js";
console.log(add(5, 3)); // 8
console.log(subtract(5, 3)); // 2
console.log(PI); // 3.14159
You can also rename a named import using the as keyword:
import { add as sum } from "./math.js";
console.log(sum(5, 3)); // 8
Importing Default Exports
With default exports, you don't use curly braces β and you can give it any name you want.
// main.js
import greet from "./greet.js";
console.log(greet("Satya")); // Hello, Satya!
Since it's a default export, naming it anything works:
import sayHello from "./greet.js"; // This also works!
console.log(sayHello("Satya")); // Hello, Satya!
Importing Everything at Once
If you want all named exports from a module, use * as:
import * as MathUtils from "./math.js";
console.log(MathUtils.add(2, 3)); // 5
console.log(MathUtils.PI); // 3.14159
Here MathUtils acts like a namespace object that holds all the exports.
Default vs Named Exports
This is one of the most confusing parts for beginners. Let me break it down clearly.
| Feature | Named Export | Default Export |
|---|---|---|
| How many per file | Multiple allowed | Only one allowed |
| Import syntax | import { name } |
import anyName |
| Curly braces needed | β Yes | β No |
| Rename on import | Use as keyword |
Any name works directly |
Example of both in the same file:
// utils.js
export const version = "1.0.0"; // Named export
export default function init() { // Default export
console.log("App initialized!");
}
Importing both together:
// main.js
import init, { version } from "./utils.js";
init(); // App initialized!
console.log(version); // 1.0.0
Notice β the default import (init) comes before the curly braces.
How to Use Modules in the Browser
To use modules in an HTML file, add type="module" to your <script> tag:
<script type="module" src="main.js"></script>
Without type="module", the browser won't understand import and export and will throw an error.
Note: Modules are automatically in strict mode. You don't need to write
"use strict"manually.
Benefits of Modular Code
Now that you know how modules work, here's why they make your life as a developer easier:
1. Better Code Organization
Each file has a clear responsibility. math.js handles math, greet.js handles greetings. Easy to navigate.
2. Reusability
Write a function once, import it anywhere. No copy-pasting the same code in multiple places.
3. Avoids Naming Conflicts
Since each module has its own scope, variables don't accidentally overwrite each other.
4. Easier to Maintain
When a bug occurs, you know exactly which file to look at. Smaller files = easier debugging.
5. Better Collaboration
Different developers can work on different modules simultaneously without stepping on each other's toes.
Conclusion
Modules are one of the most important features of modern JavaScript. They allow us to:
- Split code into smaller, focused files
- Export and share specific values between files
- Import only what we need
- Avoid naming conflicts
- Build large applications in an organized way
Without modules, building real-world applications would be chaotic.
As you move forward in JavaScript, you'll use modules constantly in:
- React / Vue / Angular projects
- Node.js applications
- Any large-scale JavaScript project
Hope you liked this blog. If thereβs any mistake or something I can improve, do tell me. You can find me on LinkedIn and X, I post more stuff there.
Top comments (0)