JAVASCRIPT / CHAPTER 12

Modules and explicit dependencies

Intermediate

Separate reusable computation from application startup.

By the end of this chapter

  • Read named imports and exports
  • Recognize live exported bindings
  • Keep module initialization predictable

The idea

An ECMAScript module explicitly exports selected bindings and imports its dependencies. The named import syntax must match the export name, although an alias can rename it locally. Modules execute in strict mode. Keep reusable functions separate from startup work so importing a helper does not unexpectedly launch a user interaction or reset stored state.

An imported binding reflects updates made by the exporting module; it is not a local assignment target. An exported object can still be mutable, so a read-only binding is not a frozen value. The example describes two files loaded as native modules by a suitable host. Resolution rules and file-loading setup belong to that host, so these fragments are not an instruction to execute multiple files in the browser editor.

JavaScript example
// counter.js
export let count = 0;
export function increment() { count++; }
// main.js
import {count, increment} from "./counter.js";
increment();
console.log(count);
Result
1

The importer reads the current exported binding after increment changes it.

Try it yourself

Split a text-normalization helper and a reporting entry point into two modules with no startup side effect in the helper.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

Open JavaScript coding challenges

CHECK YOUR UNDERSTANDING

Chapter checkpoint

Which import matches export function score() {} from scores.js?