Javascript Modules: Import And Export Explained
JavaScript modules, using the import and export keywords, allow developers to break code into smaller, reusable files, promoting better organisation, maintainability, and encapsulation. This system, introduced in ES6, is the standard for modern JavaScript development.
???? Why JavaScript Modules Are Needed:
As JavaScript applications grow, writing all your code in a single file (or loosely connected files) quickly leads to serious problems. Modules were introduced to solve these issues and bring structure to your code base.
- Global scope pollution:
JavaScript applications without modules often suffer from global scope pollution, where variables and functions are defined in the global space and become accessible from anywhere in the code.
This creates a high risk of name collisions, especially in larger projects where multiple developers are working simultaneously.
???? Example
var user = "Alice";
var user = "Bob";
console.log(user);
- Hard-to-maintain code:
Another major issue is hard-to-maintain code.
When all logic is written in a single file or a few large files, the code base quickly becomes overwhelming.
These files can grow to thousands of lines, mixing different concerns such as business logic, UI handling, and utility functions in one place.
???? Example
function login() { /* ... */ }
function calculateTotal() { /* ... */ }
function renderUI() { /* ... */ }
function sendEmail() { /* ... */ }
3.Lack of Re-usability:
The absence of modules also leads to a lack of re-usability.
Developers often end up copying and pasting the same functions across multiple files or projects instead of sharing them efficiently.
This duplication increases the size of the code base and creates maintenance challenges.
If a bug is found in a duplicated function, it must be fixed in every place where the code was copied, increasing the chances of inconsistencies and missed updates.
???? Example
function formatDate(date) {
return date.toISOString();
}
(copied again)
function formatDate(date) {
return date.toISOString();
}
Dependency Confusion:
Finally, dependency confusion is a common problem in non-modular JavaScript.
In traditional setups, especially when using multiple script tags, there is no clear indication of which file depends on another.
Developers must manually manage the order in which scripts are loaded, and even a small mistake can break the application.
???? Example
<script src="math.js"></script>
<script src="app.js"></script>
If app.js depends on math.js, the order matters.
???? Exporting Functions or Values:
In JavaScript modules, exporting functions or values allows you to make specific parts of a file available for use in other files. Instead of exposing everything globally, you explicitly choose what should be shared, which improves clarity and control.
The export keyword makes variables, functions, or classes available to other modules.
There are two types:
Named Exports
Default Exports
- Named Exports Named exports allow you to export multiple values from a single module. You can export them either individually or all at once.
Example 1: In-line Named Exports
export const username = "JohnDoe";
export const age = 25;
Example 2: Exporting All at Once
const username = "JohnDoe";
const age = 25;
export { username, age };
To import named exports, use curly braces {}:
import { username, age } from "./data.js";
console.log(username, age);
- Default Exports A module can have only one default export, which simplifies importing.
Example: Default Export
const greet = () => "Hello, welcome to JavaScript Modules!";
export default greet;
- To import a default export, do not use curly braces {}:
import greet from "./greet.js";
console.log(greet());
???? Importing Modules:
What is importing?
Importing is the process of bringing functions, variables, classes, or other code from one module (file) into another module so they can be used there.
Import Named Exports
import { add, subtract } from './math.js';
console.log(add(2, 3));
Import Default Export
import greet from './greet.js';
console.log(greet('Alice'));
Import Everything
import * as math from './math.js';
console.log(math.add(2, 3));
???? Default vs Named Exports:
Default Exports:
A default export is the main thing a module provides.
- Each file can have only ONE default export
- When importing, you can choose any name
export default function greet() {}
import greet from './greet.js';
Named Exports:
Named exports let you export multiple values from a single file, each with its own name.
- can have many named exports
- It must import them using the exact same names
⚖️ Key Differences
| Feature | Named Export | Default Export |
|---|---|---|
| Number allowed | Multiple | One per file |
| Import syntax | { name } |
Any name |
| Use case | Utilities, multiple items | Main functionality |
???? Benefits of Modular Code
Maintainability
Smaller files → easier to understand.
Changes are localized.Re-usability
Share modules across projects.Testability
Test individual modules in isolation.Team Collaboration
Multiple developers can work on different modules.Scalability
Code base grows without becoming chaotic.
???? Diagram Ideas
1️⃣ File Dependency Diagram
app.js
├── math.js
├── greet.js
└── utils.js
2️⃣ Module Import/Export Flow
[ math.js ]
| export add, subtract
↓
[ app.js ]
| import { add }
↓
Use functions
Popular Products
-
Gas Detector Meter$311.56$155.78 -
Foldable Garbage Picker Grabber Tool$93.56$46.78 -
Portable Unisex Travel Urinal$49.56$24.78 -
Reusable Keychain Pepper Spray – 20ml$21.56$10.78 -
Camping Survival Tool Set$41.56$20.78