36. What are modules in ES6?
Modules in ES6 (ECMAScript 2015) are a way to organize code into reusable, self-contained units. They provide a clean separation between the public and private parts of your application and can be used to avoid naming conflicts, reduce code duplication, and make your code more modular and maintainable.
There are two main types of modules in ES6: CommonJS modules and ES6 modules.
1. CommonJS modules: These are the traditional modules that have been used in Node.js for a long time. They use a `module.exports` object to export values from a module, and they require other modules using the `require()` function.
Here's an example of a CommonJS module:
// math.js
function add(x, y) {
return x + y;
}
module.exports = {
add: add,
};
// app.js
const math = require('./math');
console.log(math.add(2, 3)); // Output: 5
In this example, we have a `math.js` module that exports an `add()` function using the `module.exports` object. We then use the `require()` function in `app.js` to import the `math` module and call its `add()` function.
2. ES6 modules: These are new modules introduced in ECMAScript 2015 that provide a simpler and more efficient way of organizing code. They use an `import` statement to import values from a module, and they export values using the `export` keyword. Here's an example of an ES6 module:
// math.js
export function add(x, y) {
return x + y;
}
// app.js
import { add } from './math';
console.log(add(2, 3)); // Output: 5
In this example, we have an `math.js` module that exports an `add()` function using the `export` keyword. We then use the `import` statement in `app.js` to import the `add()` function from the `math` module and call it.
Overall, modules in ES6 provide a powerful way to organize code into reusable units that can be easily imported and exported between files. By using modules, you can create more modular and maintainable applications that are easier to scale and extend over time.