


Khusboo Tayal
As applications grow larger, organizing code becomes essential. JavaScript Modules help you split your code into reusable, maintainable files. They allow you to import and export pieces of code like functions, objects, classes, or variables between different files.
A module is just a JavaScript file that exports variables, functions, or classes, and can import them in other files.
By default, variables and functions in a file are private to that file unless you explicitly export them.
There are two ways to export:
You can export multiple values using named exports.
// math.js
export const PI = 3.14;
export function add(a, b) {
return a + b;
}
You can only have one default export per module.
// greet.js
export default function greet(name) {
return `Hello, ${name}`;
}// main.js
import { PI, add } from './math.js';
console.log(PI); // 3.14
console.log(add(2, 3)); // 5
You can also rename imports:
import { add as sum } from './math.js';
console.log(sum(1, 2));
import greet from './greet.js';
console.log(greet('Alice')); // Hello, AliceYou can have both in the same module:
// mixed.js
export const name = 'JavaScript';
export default function() {
console.log("This is the default function");
}
Importing:
import defaultFunc, { name } from './mixed.js';
defaultFunc();
console.log(name);Modern JavaScript environments like ES6+, Node.js (ESM), and bundlers like Webpack, Vite, and Parcel support modules.
Make sure to:
<script type="module" src="main.js"></script>
// utils.js
export function square(x) {
return x * x;
}
export default function cube(x) {
return x * x * x;
}
// app.js
import cube, { square } from './utils.js';
console.log(square(3)); // 9
console.log(cube(2)); // 8JavaScript modules make your code modular, reusable, and easier to manage. By using export and import, you can split your application into logical units and keep your codebase clean.
Key Points: