You are currently viewing JavaScript Cheat Sheet 10.51: JavaScript Modules

JavaScript Cheat Sheet 10.51: JavaScript Modules

JavaScript Modules Tutorial

Introduction to JavaScript Modules

JavaScript Modules are a way to organize code into separate files or modules, each containing its own set of variables, functions, or classes. This allows for better code organization, reuse, and maintainability. In this tutorial, we’ll cover the basics of JavaScript Modules, including how to create, import, and export modules.

1. Creating a Module

To create a module in JavaScript, simply create a new JavaScript file with a .js extension. Each file will represent a module containing related functionality.

Let’s create a module named math.js:

// math.js
export function add(a, b) {
  return a + b;
}

export function subtract(a, b) {
  return a - b;
}

In this module, we have defined two functions: add and subtract, which perform addition and subtraction operations respectively.

2. Exporting from a Module

In JavaScript, you can export variables, functions, or classes from a module using the export keyword. This makes them accessible to other modules.

In the math.js module we created earlier, we used the export keyword to export the add and subtract functions.

3. Importing into a Module

To use functions or variables from another module, you need to import them into your current module using the import keyword.

Let’s create another module named main.js and import the functions from math.js:

// main.js
import { add, subtract } from './math.js';

console.log(add(5, 3)); // Output: 8
console.log(subtract(10, 4)); // Output: 6

In this code snippet, we import the add and subtract functions from the math.js module using destructuring assignment. We then use these imported functions to perform addition and subtraction operations.

4. Using Imported Functions or Variables

Once you have imported functions or variables from a module, you can use them just like any other function or variable in your code.

In the main.js module, we imported the add and subtract functions from the math.js module and used them to perform arithmetic operations.

Conclusion

JavaScript Modules provide a way to organize and modularize your code, making it easier to manage and maintain. In this tutorial, we covered the basics of creating, exporting, and importing modules in JavaScript. Practice creating and using modules to become comfortable with this important aspect of JavaScript development.

Leave a Reply