Modules in JavaScript – Import and Export
export to share code and import to use it elsewhere. This keeps code organized, reusable, and easier to maintain.Imagine you are building a college admission portal. It manages students, courses, payments, and reports. Keeping every feature in one JavaScript file becomes difficult.
How would you organize this application as it grows? You can place related code into separate files. JavaScript modules make this possible.
1. The Problem: One Large JavaScript File
Consider a college portal with three features. It needs student details, course details, and fee calculations.
Without modules, we may keep every function in one file.
const students = [
{ name: "Priya", course: "JavaScript" },
{ name: "Ravi", course: "React" },
{ name: "Lakshmi", course: "Node.js" }
];
function getStudentCount() {
return students.length;
}
function getCourseName(student) {
return student.course;
}
function calculateAdmissionFee(amount, discount) {
return amount - discount;
}
console.log("Students:", getStudentCount());
console.log("Course:", getCourseName(students[0]));
console.log("Fee:", calculateAdmissionFee(25000, 2000));
Students: 3 Course: JavaScript Fee: 23000
This code works. But adding more features makes the file harder to manage.
What goes wrong as the application grows?
- Student, course, and payment code become mixed.
- Finding one function takes more time.
- Changing one feature can affect unrelated code.
- Reusing a function in another file becomes difficult.
- Multiple developers may edit the same large file.
Now think about a portal with hundreds of features. A single file becomes a maintenance problem.
2. What Is a JavaScript Module?
A module is a JavaScript file that can share and use code. Each module can contain variables, functions, classes, and other declarations.
We can keep each feature in its own file. Other files can import the parts they need.
3. How Import and Export Work
JavaScript modules use two main keywords.
- export = makes selected declarations available to other modules.
- import = brings exported declarations into the current module.
Let's divide our college portal into separate files.
Student data and student functionsCourse information and course functionsAdmission fee calculationImports and uses the required functionsHow does the module flow work?
4. Named Exports in JavaScript
A named export shares a declaration using its name. One file can have many named exports.
Let's create the student module first.
export const students = [
{ name: "Priya", course: "JavaScript" },
{ name: "Ravi", course: "React" },
{ name: "Lakshmi", course: "Node.js" }
];
export function getStudentCount() {
return students.length;
}
export function getStudentNames() {
return students.map(student => student.name);
}
We used export before each declaration. Other modules can now import these names.
Import named exports
Use curly braces when importing named exports. The imported names must match their exported names.
import { students, getStudentCount, getStudentNames }
from "./student.js";
console.log("Total students:", getStudentCount());
console.log("Names:", getStudentNames());
console.log("First course:", students[0].course);
Total students: 3 Names: [ 'Priya', 'Ravi', 'Lakshmi' ] First course: JavaScript
The from keyword tells JavaScript where the module lives. The path is relative to the importing file.
Rename an imported declaration
You can give an imported name a local alias. This helps when names conflict.
import {
getStudentCount as countStudents
} from "./student.js";
console.log(countStudents());
The original export name stays unchanged. Only the local imported name changes.
5. Export Declarations at the End
You do not need to write export before every declaration. You can export several declarations together.
const collegeName = "City College";
const students = [
{ name: "Priya", course: "JavaScript" },
{ name: "Ravi", course: "React" }
];
function getStudentCount() {
return students.length;
}
export { students, getStudentCount, collegeName };
This approach keeps declarations separate from the export list. Both styles are valid.
6. Default Exports in JavaScript
A default export shares one main value from a module. A module can have only one default export.
For example, the course module can provide one main function.
const courses = [
{ id: 1, name: "JavaScript", duration: "8 weeks" },
{ id: 2, name: "React", duration: "6 weeks" },
{ id: 3, name: "Node.js", duration: "7 weeks" }
];
function getAvailableCourses() {
return courses;
}
export default getAvailableCourses;
Import a default export
Default imports do not use curly braces. You can choose the local name.
import loadCourses from "./course.js";
const courses = loadCourses();
courses.forEach(course => {
console.log(course.name, "-", course.duration);
});
JavaScript - 8 weeks React - 6 weeks Node.js - 7 weeks
The name loadCourses is local to the importing file. It does not need to match the function's original name.
7. Named Export vs Default Export
| Feature | Named export | Default export |
|---|---|---|
| Count per file | Many exports | One default export |
| Import syntax | Uses curly braces | No curly braces |
| Import name | Must match or use an alias | Can choose any local name |
| Example | import { students } |
import courses |
| Common use | Several related utilities | One main value or function |
8. Export and Import Multiple Items
A module can combine named exports and one default export. This is useful for feature-based files.
export const admissionFee = 25000;
export function calculateDiscount(amount, discount) {
return amount - discount;
}
export default function getFeeDetails() {
return {
admissionFee,
currency: "INR"
};
}
import getFeeDetails, {
admissionFee,
calculateDiscount
} from "./fee.js";
console.log(getFeeDetails());
console.log(calculateDiscount(admissionFee, 2000));
{ admissionFee: 25000, currency: 'INR' }
23000
9. How the Browser Loads JavaScript Modules
Browsers support JavaScript modules through the type="module" attribute.
Use this attribute on the entry file in your HTML page.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>College Admission Portal</title>
</head>
<body>
<h1>College Admission Portal</h1>
<script type="module" src="./app.js"></script>
</body>
</html>
The browser treats app.js as a module. It can now use static imports and exports.
file:// URL. Browsers may block module loading because of security rules. Run the page through a local development server.What changes when we use modules?
- Modules use strict mode automatically.
- Each module has its own scope.
- Module imports are resolved before the module runs.
- Modules are loaded with deferred behavior in browser pages.
- Module files can import other module files.
10. Module Resolution and Execution Flow
When the browser loads app.js, it follows the imported file paths. It loads the required modules and their dependencies.
Static imports are handled before normal module execution. This is why imports usually appear at the top level.
11. Re-Exporting from Another Module
Sometimes one file needs to expose declarations from other files. We can re-export them without importing them first.
This pattern helps create a central entry point for a feature.
export {
students,
getStudentCount,
getStudentNames
} from "./student.js";
export { default as getAvailableCourses }
from "./course.js";
Now another file can import these declarations from the central file.
import {
students,
getStudentCount,
getAvailableCourses
} from "./student/index.js";
console.log(getStudentCount());
console.log(students[0].name);
console.log(getAvailableCourses().length);
This is often called a barrel file. It groups exports from multiple modules.
12. Dynamic Import in JavaScript
Static imports load dependencies through declarations at the top level. Sometimes we need a module only after an action.
Dynamic import lets us load a module when needed. It uses the import() function and returns a Promise.
A Promise represents a result that may become available later.
For example, the portal may load reports only when a user opens them.
export function getAdmissionReport() {
return [
{ course: "JavaScript", students: 40 },
{ course: "React", students: 25 }
];
}
async function showAdmissionReport() {
const reportModule = await import("./report.js");
const report = reportModule.getAdmissionReport();
console.log(report);
}
showAdmissionReport();
[
{ course: 'JavaScript', students: 40 },
{ course: 'React', students: 25 }
]
The await keyword waits for the module to load. We can then use its exported declarations.
Dynamic import flow
13. Important Rules for JavaScript Modules
1. Use file extensions in browser imports
For browser-based JavaScript, use the correct relative file path. Including .js avoids many module resolution problems.
import { getStudentCount } from "./student.js";
2. Imports are read-only bindings
An imported binding cannot be reassigned in the importing module. The exporting module may still change an exported variable.
// counter.js
export let totalStudents = 3;
// app.js
import { totalStudents } from "./counter.js";
console.log(totalStudents);
// This assignment is not allowed:
// totalStudents = 10;
3. Avoid circular dependencies when possible
A circular dependency happens when two modules depend on each other. For example, student.js imports course.js, and course.js imports student.js.
Some circular dependencies work. But they can make initialization harder to understand. Move shared logic into a third module when possible.
4. Do not confuse module paths with package names
Relative paths begin with ./ or ../. Package imports use package names and depend on the runtime or build setup.
5. Modules have their own scope
A top-level variable in one module does not become a global variable. Export it when another module needs it.
14. Common Mistakes and How to Fix Them
| Mistake | Why it happens | Fix |
|---|---|---|
| Missing curly braces | Named import syntax is incorrect. | Use import { name }. |
| Wrong export name | The imported name does not exist. | Check the exported declaration. |
| Wrong file path | The module cannot be found. | Check the relative path and extension. |
| Multiple default exports | A module allows only one default export. | Use named exports for other declarations. |
| Using import in a classic script | The script is not treated as a module. | Use type="module" in HTML. |
| Opening through file URL | Browser security can block module requests. | Use a local development server. |
15. Modules in Real Projects
Modules help us organize code by feature. A college portal could use this structure.
college-portal/
│
├── index.html
│
└── src/
├── app.js
│
├── students/
│ ├── student.js
│ └── index.js
│
├── courses/
│ └── course.js
│
├── payments/
│ └── fee.js
│
└── reports/
└── report.js
Each folder owns one feature. The entry file connects the required features.
This structure also helps teams work on separate areas. Developers can understand where each feature belongs.
Suggested design practices
- Keep each module focused on one clear responsibility.
- Export only declarations that other files need.
- Prefer named exports for shared utilities and related functions.
- Use default exports when one item is the module's main purpose.
- Avoid deeply nested and confusing import paths.
- Keep circular dependencies out of the design when possible.
- Use dynamic imports for features that should load on demand.
- Keep module names and file names consistent.
16. Interview Questions on JavaScript Modules
Q1. What is a JavaScript module?
Answer: A JavaScript module is a file with its own scope. It can export declarations and import declarations from other modules. This helps us organize large applications into smaller files.
Q2. What is the difference between named and default exports?
Answer: A module can have many named exports but only one default export. Named imports use curly braces. Default imports do not use curly braces.
Q3. Can we use multiple named exports in one file?
Answer: Yes. We can export many variables, functions, and classes. We can export them directly or use an export list.
Q4. Can we rename an imported function?
Answer: Yes. We can use the as keyword to give it a local name. The original export name does not change.
Q5. What is dynamic import?
Answer: Dynamic import loads a module when the application needs it. It uses import() and returns a Promise. We can use it with await.
Q6. Why do we use type="module"?
Answer: Browsers need this attribute to treat a script as a JavaScript module. It enables module features such as static import and export.
Q7. Can a module have more than one default export?
Answer: No. A module can have only one default export. It can still have many named exports.
Q8. What is a circular dependency?
Answer: It happens when modules depend on each other. It can make initialization difficult to follow. We can often fix it by moving shared code into another module.
17. Hands-On Practice
Try these exercises using the college admission portal example. Create separate JavaScript files for each feature.
Exercise 1: Create a student module
- Create a file named
student.js. - Export an array containing three student records.
- Export a function that returns the student count.
- Import both declarations into
app.js. - Print the count and student names.
Exercise 2: Create a course module
- Create a file named
course.js. - Add three courses with their durations.
- Use a default export for the course list function.
- Import and display all course details.
Exercise 3: Create a payment module
- Create a file named
fee.js. - Export the admission fee as a named export.
- Export a function that calculates a discount.
- Import both declarations into the application.
- Print the final fee after the discount.
Exercise 4: Load reports dynamically
- Create a file named
report.js. - Export a function that returns course admission counts.
- Use
import()inside an async function. - Print the report after the module loads.
18. Key Takeaways
- Module = a JavaScript file with its own scope.
- Export = makes selected declarations available to other modules.
- Import = brings exported declarations into another module.
- Named export = shares declarations using their names.
- Default export = shares one main declaration from a module.
- Alias = gives an imported declaration a different local name.
- Dynamic import = loads a module when the application needs it.
- Re-export = exposes declarations from another module.
JavaScript modules make applications easier to organize and maintain. Start with small files and clear responsibilities. As your application grows, this structure will help you manage its features.
19. Continue Learning with Upgradix
Keep practising JavaScript with real application examples. Build small modules first. Then connect them into a complete application.
Learn Technology. Build Your Future.
Quality Technology Education. Completely Free.