How to Create and Use JavaScript Modules


JavaScript modules are a way to organize and encapsulate code into reusable units. They promote code modularity, making it easier to maintain and collaborate on large projects. In this guide, we'll explore how to create and use JavaScript modules and provide examples to illustrate their usage.


Creating a Module


A JavaScript module can be created by encapsulating code in a separate file. Each module file can contain functions, variables, and classes that you want to export for use in other parts of your application. Here's an example of a simple module:


// myModule.js
export function sayHello(name) {
return `Hello, ${name}!`;
}
export const maxNumber = 100;
export class Calculator {
add(a, b) {
return a + b;
}
}

In this example, we create a module named myModule that exports a function, a constant, and a class.


Using a Module


To use a module in your application, you can import it using the import statement. Here's an example:


// app.js
import { sayHello, maxNumber, Calculator } from './myModule.js';
console.log(sayHello('Alice')); // Outputs: "Hello, Alice!"
console.log(maxNumber); // Outputs: 100
const calc = new Calculator();
console.log(calc.add(5, 3)); // Outputs: 8

In this example, we import the functions, constants, and classes from the myModule module into the app.js file and use them as needed.


Default Exports


You can also have a default export from a module. The default export is commonly used when a module exports a single value. Here's an example:


// math.js
const pi = 3.14159265359;
export default pi;

// app.js
import pi from './math.js';
console.log(pi); // Outputs: 3.14159265359

In this example, we have a default export of the constant pi from the math.js module.


Conclusion


JavaScript modules provide a clean and organized way to structure your code and promote reusability. They are a fundamental part of modern web development, enabling you to create maintainable and scalable applications. By creating and using modules, you can better manage your codebase and collaborate with others effectively.


Happy coding with JavaScript modules!