AI Hints
Home›JavaScript Tutorial›Modules, Dates and Math
JavaScript · Lesson 76 of 138

Modules

Import and export.

⏱ 2 min read▶ Video at 1:32:05🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

Real programs have thousands of lines. Putting them all in one file would be chaos. Modules let you split code into files, and share only what you choose, with export and import.

Modules
From the video: Modules
  • Thousands of lines
  • One file is chaos
  • Modules: export and import

Two files

A separate file, utils dot MJS, exports a constant, a function, and a default function. In our app, import pulls them in. Named exports go in curly braces, and the default export can be given any name. Run it.

app.mjsjavascript
import formatMoney, { TAX, withTax } from "./utils.mjs";

const price = 50;
console.log("Tax rate:", TAX);
console.log("With tax:", formatMoney(withTax(price)));
Output
Tax rate: 0.2
With tax: $60.00
Also uses utils.mjs
export const TAX = 0.2;

export function withTax(price) {
  return price * (1 + TAX);
}

export default function formatMoney(n) {
  return `$${n.toFixed(2)}`;
}

Why modules help

Each module has its own scope, so its variables don't leak out unless exported. Files stay small and focused. In Node, files ending in dot MJS use these modules, or you can set type module in package dot JSON. In the browser, a script tag with type equals module does the same.

keyvalue
exportshare from a file
import { a } fromnamed import
import x fromdefault import
Own scopenothing leaks

Summary

Modules split code into files. Export shares values, and import uses them. Next, working with dates.

Key takeaways
  • export / export default
  • import { } from
  • Small, focused files
Next up: Dates — working with time