In modern JavaScript, every file is its own "module." Variables and functions inside a file are private unless you explicitly Export them.
1. Export
You use the export keyword to make a function, object, or variable available for use in other files.
Named Export: You can export multiple things from one file.
Default Export: You export one main thing from a file.
2. Import
You use the import keyword to "pull in" the code you need from another file.
3. Why use them?
It prevents "Global Scope Pollution" (where different scripts accidentally overwrite each other's variables) and makes code much easier to test.
The Code Example
Imagine we have two separate files:File 1: mathUtils.js
// Exporting specific functions (Named Exports)
export const add = (a, b) => a + b;
export const PI = 3.14159;
// Exporting a main class (Default Export)
export default class Calculator {
multiply(a, b) {
return a * b;
}
}File 2: app.js
// 1. Importing Named Exports using curly braces
import { add, PI } from './mathUtils.js';
// 2. Importing the Default Export (no curly braces needed)
import Calculator from './mathUtils.js';
console.log(add(5, 10)); // 15
console.log(PI); // 3.14159
const calc = new Calculator();
console.log(calc.multiply(4, 5)); // 20Note: To run this in a browser, your HTML script tag needs type="module": <script type="module" src="app.js"></script>.