Modules and Import/Export statements

Modules in JavaScript are a way to organize and reuse code, by splitting it into smaller, self-contained units. A module is a script that defines a collection of functions, objects, and values that can be exported and imported by other scripts.

The import and export statements are used to include and share code between modules.

The export statement is used to export values, functions, or objects from a module so they can be used in other modules. The syntax for exporting values from a module is:

// module1.js export const value = 42; export function printValue() { console.log(value); }


The import statement is used to import values, functions, or objects from another module into the current module. The syntax for importing values from a module is:

// module2.js

import { value, printValue } from "./module1.js";

console.log(value); // 42

printValue(); // 42

Modules and import/export statements are a fundamental part of modern JavaScript development and are used to modularize and organize code into smaller, more manageable units. They also make it possible to share code between different scripts and applications.