R
Rishtaara
JavaScript Fundamentals
Lesson 21 of 28Article14 min

Modules

Modules split code into separate files. Each file can export what others need and hide private details. Big apps stay organized.

Why modules matter

Modules split code into separate files. Each file can export what others need and hide private details. Big apps stay organized.

Real-life example: A school has separate departments — math, science, sports. Each department shares only what others need; internal notes stay private.

  • One file = one responsibility (utils, api, components).
  • Avoid global variables polluting window.
  • Use type="module" in script tags or bundlers like Vite.

Named export and import

Named exports let you share many values from one file. Import them with curly braces and matching names.

Real-life example: A toolbox with labeled tools — export hammer, export screwdriver. You pick only the tools you need for today's job.

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

// app.js
import { add, subtract } from "./math.js";
console.log(add(5, 3)); // 8

Default export and import

Each file can have one default export — the main thing that file provides. Import it with any name you choose.

Real-life example: A book's main author (default export) is on the cover. Supporting writers (named exports) are listed inside.

Default export
// greet.js
export default function greet(name) {
  return `Welcome to Rishtaara, ${name}!`;
}

// main.js
import greet from "./greet.js";
console.log(greet("Asha"));

Using modules in HTML

Add type="module" to your script tag. The browser loads imports automatically. File paths need .js and often start with ./ for local files.

Real-life example: Module script is like a main chapter that says "also read page 5 and page 9" — the browser fetches those pages in order.

Module script in HTML
<script type="module" src="./main.js"></script>
<!-- main.js can import from ./utils.js -->