JavaScript · Intermediate level

Intermediate level · Module 1: Modern JavaScript Syntax and Modules · Lesson 3 of 3

ES Modules

Split code into modules with import and export and load them in the browser and Node.js.

In this lesson you will

  • Export and import values between modules
  • Organise a project into modules with clear responsibilities

Key concepts

export and export defaultimporttype="module"module scope

The lesson

A module is a file with its own scope. It shares values with export (export function formatSSP…) and uses others with import (import { formatSSP } from "./format.js";). Named exports are clearer than default exports in most projects.

In the browser, load the entry file (main.js) with a script element that has type="module". Modules load over HTTP, so run a local development server instead of opening the file directly. In Node.js, use the .mjs extension or set "type": "module" in package.json.

Give each module one responsibility — data and rules, formatting, API calls, the user interface — and avoid circular imports between them.

Step by step

  1. Create format.js and export a formatting function.
  2. Import it into main.js.
  3. Load main.js as a module through a local server.
  4. Split the remaining code into data and UI modules.

Practice activity

Complete the module refactor from the practical activity.

Expected result: The app behaves exactly as before, with code split into three or more modules and no global variables.

Check your understanding

  1. Why do browser modules need a local server?

    Show answer

    Modules are loaded over HTTP and browsers block them from file:// URLs.

  2. What is module scope?

    Show answer

    Variables in a module are private to it unless exported.

Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.