JavaScript Modules

Modern JavaScript uses ES6 modules to organize code into reusable, encapsulated files. This tutorial covers the basics of import and export, dynamic imports, and how to run modules in the browser.

Static Imports & Exports

Use export to expose variables, functions, or classes from a module, and import to consume them.

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

// main.js
import { add, PI } from './utils.js';
console.log('2 + 3 =', add(2, 3));
console.log('π =', PI);

Default Export

A module can have a single default export. Import it without braces.

// logger.js
export default function log(msg) {
  console.log('[LOG]', msg);
}

// app.js
import log from './logger.js';
log('App started');

Dynamic Import

Load a module only when needed using import(). Perfect for code‑splitting.

// click the button to load the module

Try It Live

Below is an inline module you can edit and run instantly.