1. Importing and Exporting Modules

Introduction to Modules

JavaScript modules allow you to break down your code into reusable, manageable pieces. Each module is a separate file that can export values, functions, objects, or classes, and these exports can then be imported into other modules. This modular approach helps improve code organization, maintainability, and reusability.

Exporting from a Module

To export something from a module, you use the export keyword. There are two main types of exports: named exports and default exports.

Named Exports

Named exports allow you to export multiple values from a module. Each exported value must be explicitly specified.

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

Default Exports

Default exports are used to export a single value from a module. This can be a function, class, object, or any other value.

// logger.js
export default function log(message) {
  console.log(message);
}

Importing from a Module

To import values from a module, you use the import keyword. The syntax varies depending on whether you are importing named exports or a default export.

Importing Named Exports

You can import named exports using curly braces. You can import multiple named exports from the same module.

// app.js
import { pi, add } from './math.js';

console.log(pi); // 3.14159
console.log(add(2, 3)); // 5

Importing a Default Export

When importing a default export, you do not use curly braces. You can give the imported value any name you like.