Modules in JavaScript
Modules in JavaScript
Hello! In this guide, we’ll explore how modules work in JavaScript. Modules are an essential part of modern JavaScript development, allowing developers to break code into reusable pieces and manage dependencies. Let’s get started!
Video Explanation

1. What Are Modules?
Modules in JavaScript are reusable blocks of code, encapsulated within their own scope. They allow developers to divide the code into smaller, manageable files and export functionality from one module to be used in other modules.
2. Exporting and Importing Modules
2.1 Exporting
There are two types of exports in JavaScript modules:
Named Exports
You can export multiple things from a module using named exports.
Example:
// math.js
export function add(x, y) {
return x + y;
}
export function subtract(x, y) {
return x - y;
}
Exporting an Object:
// utility.js
const utilities = {
greet: function (name) {
return `Hello, ${name}`;
},
farewell: function (name) {
return `Goodbye, ${name}`;
},
};
export { utilities };
Default Export
You can export a single value, class, or function as the default export from a module.
Example:
// logger.js
export default function log(message) {
console.log(message);
}
2.2 Importing
To use exported functions, variables, or classes from a module, you can import them using the import statement.