Mark As Completed Discussion

Module System

The module system in JavaScript provides a way to organize and structure code by splitting it into separate files called modules. Each module can export values, such as variables, functions, or classes, that can be used in other modules. Modules can also import these exported values from other modules.

Exporting Values

To export a value from a module, you can use the export keyword followed by the value or values you want to export. For example, to export a single value:

JAVASCRIPT
1export const message = 'Hello, world!';

Or to export multiple values:

JAVASCRIPT
1export const name = 'John Doe';
2export const age = 30;

Importing Values

To import values from a module, you can use the import keyword followed by the value or values you want to import, enclosed in curly braces. For example, to import a single value:

JAVASCRIPT
1import { message } from './module';

Or to import multiple values:

JAVASCRIPT
1import { name, age } from './module';

Renaming Imports and Exports

If you want to use a different name for an imported or exported value, you can use the as keyword to rename it. For example, to export a value with a different name:

JAVASCRIPT
1export { message as greeting };

And to import a value with a different name:

JAVASCRIPT
1import { greeting as welcome } from './module';

Default Exports

In addition to named exports, a module can also have a default export. This is the primary value or functionality that the module exports by default. To define a default export, you can use the default keyword. For example:

JAVASCRIPT
1// module.js
2
3export default function sayHello(name) {
4  console.log(`Hello, ${name}!`);
5}
6
7// app.js
8
9import sayHello from './module';
10
11sayHello('John');
JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment