All topics
ES6+beginner

ES Modules: import and export

The native, standardized module system for splitting JavaScript code across files, replacing older ad-hoc patterns like CommonJS and IIFEs for the browser.

ES Modules (ESM), standardized in ES6, give JavaScript a native way to split code across multiple files with explicit import/export relationships, replacing the ad-hoc patterns that came before it. Since virtually all modern JavaScript, in both the browser and Node, is organized into modules, fluent knowledge of import/export syntax and semantics is assumed baseline knowledge in interviews.

ES Modules are like a well-organized library's card catalog: each book is only ever shelved and cataloged once no matter how many patrons check its card, and if the book's contents update in place, every patron's reference reflects the update.

Key Concepts

1
A module exports values with export — either named exports, of which a module can have any number, or a single export default, of which a module can have at most one. Another file imports these with import { foo } from './module.js' for named exports, or import foo from './module.js' for a default export.
2
Modules are automatically strict mode, have their own top-level scope, and are evaluated only once no matter how many other files import them. Crucially, ESM imports are 'live bindings,' not copied values: if a module's internal state changes after being exported, code that imported it sees the updated value on next access.
3
Browsers load ES modules with script type='module'. Node.js supports ESM alongside CommonJS, distinguished by file extension (.mjs) or a type field in package.json.