Skip to content
Concept 70 // Module 07: Collections, Iteration & Modules

CommonJS vs ES Modules, Dynamic import() & Top-Level await

Module 07: Collections, Iteration & Modules•Concept 70 of 100• 5 min read

CommonJS vs ES Modules, Dynamic import() & Top-Level await

Top-Level Await allows the `await` keyword to be used outside of `async` function bodies at the top level of **ES Modules**. It enables modules to act as asynchronous resources that coordinate before dependent modules evaluate.

The Core Concept

Top-level await blocks the evaluation of modules that import it, but does not block sibling module evaluation, ensuring optimal parallel loading graphs.

Syntax Reference
// In an ES Module (.mjs or script type="module")
const res = await fetch("https://api.example.com/config");
export const config = await res.json();

Live Interactive Studio

Any module importing `db.js` will wait until `db.js` finishes awaiting before executing its own code.
JavaScript Editor
Loading...
Console Output
Waiting for output...

Key Code Patterns in Action

01

Asynchronous Resource Initialization

// db.js
console.log("1. Connecting to DB...");
// export const connection = await connectDatabase();
console.log("2. DB Connected!");

// app.js
// import { connection } from './db.js';
// console.log("3. App started with connection!");
Any module importing `db.js` will wait until `db.js` finishes awaiting before executing its own code.
02

Dynamic Fallback Module Loading

let databaseService;
try {
  databaseService = await import("./productionDb.js");
} catch (err) {
  databaseService = await import("./mockDb.js");
}
export { databaseService };
Top-level await simplifies conditional asynchronous module imports.
03

1. Core Usage: CommonJS vs ES Modules, Dynamic import() & Top-Level await

// Core syntax and usage for CommonJS vs ES Modules, Dynamic import() & Top-Level await
const feature = 'commonjs-vs-es-modules-dynamic-import-top-level-await';
console.log('Concept 70:', feature);
console.log('Active:', true);
Illustrates the fundamental invocation and syntax structure for CommonJS vs ES Modules, Dynamic import() & Top-Level await.
04

2. Defensive Handling & Edge Case

// Edge-case defensive handling
function handleSafe(input) {
  if (input === null || input === undefined) return 'safe-fallback';
  return String(input).trim();
}
console.log(handleSafe('commonjs-vs-es-modules-dynamic-import-top-level-await'));
console.log(handleSafe(null));
Shows how to write defensive, safe JavaScript code that handles nullish or unexpected inputs when working with CommonJS vs ES Modules, Dynamic import() & Top-Level await.
05

3. Clean Architecture & Production Pattern

// Production-grade pattern for CommonJS vs ES Modules, Dynamic import() & Top-Level await
const settings = Object.freeze({
  id: 'commonjs-vs-es-modules-dynamic-import-top-level-await',
  ready: true,
  timestamp: Date.now()
});
console.log('Settings initialized:', settings.id, settings.ready);
Demonstrates clean, immutable production code avoiding unintended state mutations.

Real-World Engineering Takeaways

Dynamic Configuration: Fetching runtime environment settings before application bootstrap.
WebAssembly Loading: `const wasm = await WebAssembly.instantiateStreaming(...)`.
Database Connection Pooling: Guaranteeing DB connection pools are active before servicing queries.

Under the Hood: Engine & Memory Mechanics

How JavaScript Executes This
The module graph is evaluated as a Promise graph. The engine suspends module execution, registers the awaiting promise, and continues evaluating independent module branches.

Quick Knowledge Check

Test your understanding on these 10 questions (one by one):

Score: 0 / 10
Question 1 of 10 • Core Purpose & Mental Model

What is the core purpose of CommonJS vs ES Modules, Dynamic import() & Top-Level await in JavaScript?

// Concept 70: CommonJS vs ES Modules, Dynamic import() & Top-Level await
// Understanding the core mental model
1 / 10