JavaScript Modules - Exercise 1

A module is a JavaScript file with its own scope that can share selected values through export and import.

javascript

// math.js
export function add(first, second) {
  return first + second;
}

Place export before a declaration or export several declarations together at the end of the file.

javascript

export const taxRate = 0.2;
export function addTax(price) {
  return price * (1 + taxRate);
}

Use curly braces and the exact names that the exporting module made available. Named imports are local bindings, so addTax refers to the exported function in this example.

javascript

import { taxRate, addTax } from './prices.js';
console.log(addTax(10));

Use the as keyword to give a named import a different local name. The alias changes only the importing file and does not rename the original export.

javascript

import { formatDate as formatForDisplay } from './dates.js';
console.log(formatForDisplay(new Date()));

No. Module declarations are private to that module unless explicitly exported.

javascript

// config.js
const secretKey = 'private';
export const apiUrl = '/api';
// secretKey cannot be imported from another module.

Load a browser entry file with type="module" so the browser enables import and export. Module scripts are deferred by default and follow module loading rules.

javascript

<script type="module" src="./main.js"></script>

Browsers enforce module and CORS rules, so opening an entry file with file:// can block imports. Serve the folder over HTTP instead, for example with npx serve ..

javascript

npx serve .

Declare the values normally, then list their names in an export statement.

javascript

const min = 1;
const max = 10;
function randomNumber() { return min + Math.random() * max; }
export { min, max, randomNumber };

Use export default for the module's primary value, then choose any local name when importing it.

javascript

// logger.js
export default function log(message) {
  console.log(message);
}
// app.js
import log from './logger.js';

An imported binding reflects updates from the exporting module, rather than copying the value at import time.

javascript

// counter.js
export let count = 0;
export function increment() { count++; }
// app.js sees the updated count after increment().
All sections expanded. Activate the control to collapse all sections.