Skip to main content

Command Palette

Search for a command to run...

JavaScript Modules Import and Export Explained

Updated
•3 min read•View as Markdown
JavaScript Modules  Import and Export Explained

JavaScript Modules
Why Modules Are Needed
First, understand the problem
Imagine you are building a project that includes:

  • login code

  • payment code

  • UI code

  • API code

If you write everything in one single file, it will look like this:

login code...
payment code...
UI code...
API code...

Problems:

  • the code becomes very messy

  • it becomes difficult to understand

  • fixing one part may break another part

  • teamwork becomes difficult

To solve this problem, we use modules

What is a Module
A module means:
Dividing code into smaller parts (files)

Example:

login.js
payment.js
api.js
main.js

Each file handles its own specific task.

Exporting Functions or Values
If you want to use code from one file in another file, you need to export it.
Example:

// math.js
export function add(a, b) {
  return a + b;
}

export const PI = 3.14;

Here we are exporting add and PI.

Importing Modules
Now we use it in another file:

// main.js
import { add, PI } from "./math.js";

console.log(add(2,3));
console.log(PI);

By importing, we can use code from another file.

Default vs Named Exports

🔹 Named Export
You can export multiple things:

// math.js
export function add(a, b) {
  return a + b;
}

export function sub(a, b) {
  return a - b;
}

Import:

import { add, sub } from "./math.js";

You must use the same names.

🔹 Default Export
Only one default export per file.

// greet.js
export default function greet() {
  console.log("Hello");
}

Import:

import greet from "./greet.js";

You can rename it:

import myFunc from "./greet.js";

Difference (Important)

Feature Named Export Default Export
Count Multiple Only one
Import Uses {} No {}
Rename Not allowed Allowed

Benefits of Modular Code

1. Clean Code
Code is divided into smaller parts.

2. Easy Maintenance
Fixing bugs becomes easier.

3. Reusability
You can reuse modules in multiple places.

4. Easier Teamwork
Different developers can work on different files.

5. Scalability
Large projects become easier to manage.

Real-Life Analogy

Imagine a company:

  • HR department

  • Accounts department

  • IT department

Each department does its own work, but together they form one company.

That is exactly how modules work.

Final Flow (Simple Understanding)

Small files (modules)
        ↓
Export functions/data
        ↓
Import where needed
        ↓
Build complete application

Short Summary

  • Modules = splitting code into separate files

  • Export = sharing code

  • Import = using that code