How to Use JavaScript Modules - Practical Examples


JavaScript modules allow you to organize and encapsulate your code into separate files, making your application more modular and maintainable. In this guide, we'll explore how to use JavaScript modules with practical examples to illustrate their usage.


Creating a Module


In JavaScript, you can create a module by defining your code in a separate file and exporting functions, variables, or objects that you want to make available to other parts of your application. Let's create a simple module:


Module File (myModule.js)


// Define a function to be exported
function sayHello(name) {
console.log(`Hello, ${name}!`);
}
// Export the function
export { sayHello };

Importing and Using a Module


You can import and use a module in another JavaScript file. Here's how you can import the sayHello function from the module we created:


Main File (app.js)


// Import the function from the module
import { sayHello } from './myModule.js';
// Use the imported function
sayHello('Alice');

When you run app.js, it will import the sayHello function from myModule.js and use it to greet Alice.


Exporting and Importing Multiple Functions


You can export and import multiple functions or variables from a module. Here's an example:


Module File (mathModule.js)


// Define functions to be exported
function add(a, b) {
return a + b;
}
function subtract(a, b) {
return a - b;
}
// Export the functions
export { add, subtract };

Main File (calculator.js)


// Import multiple functions from the module
import { add, subtract } from './mathModule.js';
// Use the imported functions
const result1 = add(5, 3);
const result2 = subtract(10, 4);
console.log('Addition result:', result1);
console.log('Subtraction result:', result2);

Default Exports and Imports


You can also use default exports and imports. A module can have one default export, and when you import it, you don't need to use curly braces. Here's an example:


Module File (defaultModule.js)


// Define a function as the default export
export default function greet(name) {
console.log(`Greetings, ${name}!`);
}

Main File (app.js)


// Import the default function from the module
import greet from './defaultModule.js';
// Use the imported default function
greet('Bob');

Default exports make it simpler to import and use a single function or object from a module.


Conclusion


JavaScript modules provide a structured way to organize your code, making it more maintainable and easier to collaborate on projects. By defining, exporting, and importing functions and variables from modules, you can create a modular and organized application. JavaScript modules are a fundamental feature of modern web development, and mastering them will help you become a more efficient and productive developer.


Happy coding with JavaScript modules!