JavaScript Modules - Exercise 1

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

// 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.

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

Use curly braces and the exact exported names.

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

Use the as keyword when the local name should differ.

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

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

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

Use type="module" on the entry script.

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

Browsers enforce module and CORS rules; opening an entry file with file:// can block imports. Use a local development server.

npx serve .

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

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