Mark As Completed Discussion

Modules

Modules are an essential concept in ES6+ that allow us to organize and manage our code more efficiently. They provide a way to split our code into separate files, making it easier to maintain and reuse.

Import and Export

We can use the import and export keywords to import and export code between modules.

Here's an example of how to import and use a function from another module:

JAVASCRIPT
1// utils.js
2export const calculateArea = (width, height) => {
3  return width * height;
4}
5
6// main.js
7import { calculateArea } from './utils.js';
8
9const width = 10;
10const height = 5;
11
12const area = calculateArea(width, height);
13console.log(`The area is: ${area}`);

In this example, we have a utils.js module that exports a calculateArea function. We then import that function in our main.js module and use it to calculate the area of a rectangle.

Benefits of Modules

Modules offer several benefits:

  • Code organization: Modules allow us to organize our code into logical, self-contained units.
  • Encapsulation: By encapsulating code within modules, we can control the visibility of variables and functions, preventing them from polluting the global scope.
  • Code reuse: With modules, we can easily reuse code in different parts of our application or even in multiple projects.

Modules are a powerful feature of ES6+ that help us write modular and maintainable code.

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment