Modules and Imports
Learn how to split code into modules, import and export between files, and organize larger programs effectively.
What you'll learn
- What modules are and why they matter for code organization
- How to export functions, variables, and objects from a file
- How to import what you need from another module
- Default exports vs. named exports
- How modules prevent global namespace pollution
Concept
Modules and Imports
A module is a self-contained file of code that can be shared between different parts of a program. As programs grow, putting everything in one file becomes unmanageable. Modules let you split code into logical units — one file for user functions, another for database helpers, another for UI components — and connect them with imports and exports.
Why Modules?
Without modules, every variable and function lives in the global scope. In a large project, names collide: two files both define a validate function, and the second one silently overwrites the first. Modules solve this by giving each file its own scope. Nothing is global unless you explicitly export it.
Modules also make code reusable: you write a utility once in mathUtils.js and import it wherever you need it. And they make code testable: you can import a single module in isolation and verify its behavior without loading the entire application.
Exporting
JavaScript ES modules use the export keyword to share code from a module:
// mathUtils.js
export function add(a, b) { return a + b; } // named export
export function subtract(a, b) { return a - b; } // named export
export const PI = 3.14159; // named export
// A module can have one default export:
export default function multiply(a, b) { return a * b; }
Importing
Other files bring in the exported code with import:
// app.js
import multiply, { add, subtract, PI } from "./mathUtils.js";
add(2, 3); // 5
multiply(4, 5); // 20 (default export, no braces)
Named exports are imported with braces: { add, subtract }. The default export is imported without braces and you can rename it freely. A module can have many named exports but only one default.
Default vs. Named Exports
- Default export — the "main" thing the module provides. Use it when a module has one primary purpose:
export default class User { ... }. - Named exports — for modules that provide several related utilities. They require exact name matching on import, which helps with autocomplete and refactoring.
Module Resolution
When you write import { x } from "./utils", the system resolves the path: ./utils means "in the same directory." Node.js and bundlers (Vite, webpack) handle the resolution, finding the right file and connecting the exports to the imports. You just write the path and the names.
Best Practices
Keep modules focused — one module, one responsibility. Prefer named exports for utilities (they are explicit and refactor-safe). Use default exports for the primary class or function a module is built around. Avoid circular dependencies where module A imports module B and B imports A — it creates initialization order problems that are hard to debug.
Example
// --- file: validators.js ---
export function isEmail(text) {
return text.includes("@") && text.includes(".");
}
export function isPhoneNumber(text) {
return /^\d{3}-\d{3}-\d{4}$/.test(text);
}
export function minLength(text, n) {
return text.length >= n;
}
// --- file: formHelpers.js ---
import { isEmail, minLength } from "./validators.js";
export function validateSignupForm(email, password) {
const errors = [];
if (!isEmail(email)) errors.push("Invalid email");
if (!minLength(password, 8)) errors.push("Password too short");
return errors;
}
// --- file: app.js ---
import { validateSignupForm } from "./formHelpers.js";
const errors = validateSignupForm("ada@test.com", "secret");
console.log(errors); // ["Password too short"]
const valid = validateSignupForm("ada@test.com", "securepass");
console.log(valid); // [] (no errors)
validators.js exports three named functions. formHelpers.js imports two of them and exports its own function. app.js imports from formHelpers. Each file has its own scope — no global pollution.
Try it
- JSON to TypeScript
TypeScript interfaces are often exported from modules. See how data shapes are defined and shared across files.
- Code Minifier
Minifiers process modules — renaming internal variables while preserving exported names. See the boundary between internal and external.
Common mistakes
The mistake
Mixing up default and named import syntax.
The fix
Default imports have no braces: import x from './mod'. Named imports use braces: import { x } from './mod'. Mixing them causes syntax errors or undefined values.
The mistake
Creating circular dependencies (A imports B, B imports A).
The fix
Refactor so the shared code lives in a third module that both A and B import. Circular dependencies cause undefined values at runtime because one module is not fully initialized when the other tries to use it.
The mistake
Exporting everything from a module, treating it like a global bag of functions.
The fix
Only export what other modules actually need. Keep internal helpers unexported. A focused public API makes the module easier to understand and harder to misuse.
Related Resources
Related Cheatsheets
- JavaScript Cheatsheet
Reference for import/export syntax, default vs. named exports, and module patterns.
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.