Modules in JavaScript are small, self-contained units of code that encapsulate functionality and data, allowing developers to create reusable building blocks for building complex applications. They enable developers to define private and public members separately, following the principle of encapsulation, which is a key aspect of object-oriented programming. By organizing code into modules, developers can manage complexity, improve code maintainability, and promote code reuse. This modular approach is considered one of the fundamental design patterns in JavaScript development, facilitating the creation of scalable and maintainable applications.
ECMAScript Modules are the official standard for JavaScript modules, supported in modern browsers and in recent versions of Node.js. In ESM, you use import and export statements to define the interface of a module.
Example:
// imp.js
const greet = require('./exp');
console.log(greet('Coders')); // Output: Welcome, Coders!
// exp.js
module.exports = function(name) {
return `Welcome, ${name}!`;
};