JavaScript Modules: Import and Export
What Are Modules And Why Are They Needed?
A module is just a separate file of code that you can export from and import into other files. Each module has its own scope.
Before modules, JavaScript code was often written in one large file, creating problems like:
Global scope pollution (variables clash)
Hard to manage large codebases
Difficult to debug
Poor reusability
Team collaboration becomes messy
As projects grow, this becomes unmaintainable.
Exporting Functions or Values
To make something available outside a file, we use export
Named Export:
// math.js
export function add(a, b) {
return a + b;
}
export const PI = 3.14;
Importing Modules
To use exported things in another file:
// app.js
import { add, PI } from "./math.js";
console.log(add(2, 3));
console.log(PI);//3.14
Default Export:
A function thats exported with a default can be imported in another file with a different name, example:
// file.js
export default function greet() {
console.log("Hello");
}
Only one per file
import greetUser from "./file.js"; // name can be anything
Quick Comparison
| Feature | Named Export | Default Export |
|---|---|---|
| Number allowed | Multiple | One |
| Import name | Must match | Any name |
| Syntax | {} required |
No {} |
Benefits of Modular Code
1. Better Organization
2. Reusability
3. Maintainability
4. Avoid Global Scope Pollution
5. Team Collaboration
How Modules Improve Maintainability
Without Modules:
1 big file → hard to edit → high risk of breaking code
With Modules:
small files → easy to update → less risk
Fixing one module doesn’t affect the whole system.
Conclusion
Using import and export modules in code base is a great practice to follow, as it makes it easier to track, edit, maintain, and add code. Even if the project is not considerably large, using import and export modules is considered good.