What Are Modules in JavaScript: Explanation and Examples
modules are reusable pieces of code that can export variables, functions, or classes and import them into other files. They help organize code by splitting it into smaller, manageable parts that can be shared and maintained easily.How It Works
Think of JavaScript modules like separate rooms in a house. Each room has its own furniture and tools (code), and you can open the door to share or borrow things from another room. Modules let you keep your code organized by putting related parts together in one file.
When you use a module, you export the parts you want to share, like functions or variables, and import them in another file where you need them. This way, you avoid mixing all your code in one big file, making it easier to read and fix bugs.
Example
This example shows how to create a module that exports a function and how to import and use it in another file.
// mathUtils.js export function add(a, b) { return a + b; } // main.js import { add } from './mathUtils.js'; console.log(add(5, 3));
When to Use
Use modules whenever your JavaScript code grows beyond a few lines or when you want to reuse code in different parts of your project. Modules help keep your code clean and easy to maintain.
For example, in a web app, you might have separate modules for handling user input, data fetching, and displaying content. This separation makes it easier to update one part without breaking others.
Key Points
- Modules let you split code into smaller, reusable files.
- You use
exportto share code andimportto use it elsewhere. - Modules improve code organization and maintenance.
- Modern JavaScript uses ES modules with
importandexportkeywords.
Key Takeaways
export to share and import to use code between files.