JavaScript Modules: Import and Export Explained

function add(a, b) {
return a + b;
}
function multiply(a, b) {
return a * b;
}
function log(message) {
console.log(message);
}
const sum = add(2, 3);
const product = multiply(2, 3);
log(`Sum: ${sum}`);
log(`Product: ${product}`);
Most people start writing code like this. This works for small scripts. It breaks down fast as the project grows.
All logic is mixed together. There is no separation of concerns. You can easily overwrite functions or create naming conflicts without noticing.
What Modules Actually Do
Modules solve this by splitting code into files.Each file becomes its own unit with private scope. Nothing inside a file is accessible unless you export it.This forces structure. Instead of one big file, you group code by responsibility.
Exporting Code
You export only what other files need. Named exports are used when a file exposes multiple things.
// utils.js
export function add(a, b) {
return a + b;
}
export function multiply(a, b) {
return a * b;
}
Here, both functions are explicitly exposed. Anything not exported stays private. Default export is used when a file has one main responsibility.
// logger.js
export default function log(message) {
console.log(message);
}
You can only have one default export per file. It represents the primary purpose of that module.
Importing Code
Now you bring these modules into another file.
// app.js
import log from "./logger.js";
import { add, multiply } from "./utils.js";
const sum = add(2, 3);
const product = multiply(2, 3);
log(`Sum: ${sum}`);
log(`Product: ${product}`);
Default import does not use braces. Named imports must match the exported names exactly. If you try to import something that was not exported, it will fail. This makes dependencies explicit and predictable.
Putting It Together
Now your codebase is split:
utils.js handles calculations
logger.js handles logging
app.js acts as the entry point
Each file has a clear job. app.js depends on other modules, but those modules do not depend on each other. This reduces coupling and makes the system easier to reason about.
Why This Matters
When your project grows, this structure saves you. You can update utils.js without touching app.js. You can reuse the same utilities in another project without copying random code. Debugging becomes easier because you know where to look. Bugs stay contained instead of spreading across one giant file. If you are still writing everything in one file beyond small scripts, you are slowing yourself down. Modules are the baseline for writing scalable JavaScript.




