Modules
📦JavaScript modules allow you to break your code into smaller, reusable pieces. This improves maintainability, readability, and debugging. With modules, you can import and export code across different files.
To share code from one file (module), use the export
keyword:
// math.js
export function add(a, b) {
return a + b;
}
export function subtract(a, b) {
return a - b;
}
To use code from another module, use the import
keyword:
// app.js
import { add, subtract } from './math.js';
console.log(add(2, 3)); // 5
console.log(subtract(5, 3)); // 2
For a single export from a module, you can use the default export:
// math.js
export default function multiply(a, b) {
return a * b;
}
Then, import it like this:
// app.js
import multiply from './math.js';
console.log(multiply(2, 3)); // 6
Click to see how modules work in a simplified setup:
export
to expose functions or variables from a module.import
to bring in functions or variables from another module.export default
when exporting a single item from a module.type="module"
for client-side JavaScript.
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!