Modules in JavaScript

Ronald Alexander
2 min readDec 25, 2022

--

Photo by Glen Carrie on Unsplash

Modules

Modules in JavaScript are a way to organize and structure your code by separating it into smaller, reusable pieces. They can help to make your code more maintainable, easier to understand, and easier to test.

In JavaScript, modules are typically used to define functions, objects, and classes that can be imported and used in other parts of your code. They are usually stored in separate files, which can then be imported into your main code using the import statement.

For example, let’s say you have a utility module that contains a few utility functions that you want to use in multiple parts of your code. You could define this utility module in a file called utility.js like this:

// utility.js
export function add(x, y) {
return x + y;
}
export function subtract(x, y) {
return x - y;
}
export function multiply(x, y) {
return x * y;
}
export function divide(x, y) {
return x / y;
}

To use these utility functions in another part of your code, you would need to import them using the import statement. For example:

import { add, subtract } from './utility';
console.log(add(1, 2)); // 3
console.log(subtract(5, 3)); // 2

In this example, we are using the import statement to import the add and subtract functions from the utility module, which is stored in the utility.js file.

There are a few different ways you can import and export modules in JavaScript, depending on your needs. For example, you can use the export default syntax to define a default export for your module, which can be imported using the import statement without the curly braces. You can also use the export * syntax to export all the functions, objects, and variables defined in a module.

Modules can be a very useful tool for organizing and structuring your code, and can help to make it easier to reuse and maintain. Whether you are working on a small project or a large, complex application, using modules can help you to write cleaner, more organized code.

--

--

Ronald Alexander

Full-stack developer, data scientist, and QA professional. Always learning and sharing knowledge through courses, blogging, and open source contributions.