Course contentsShow
← JavaScript
Lesson 1978 of 2,72341. Modern JavaScript Features (ES2020+)Free lesson

What is Top-Level Await

Top-level await allows using await outside async functions at the module's top level.

What is Top-Level Await

You'll learn what top-level await is and why it changed how we write module code in modern JavaScript.

The Old Restriction

Before ES2022, you could only use await inside async functions. If you needed to load data at the module level, you had two awkward choices: wrap everything in an immediately-invoked async function, or export a promise that consumers had to handle. This made simple initialization unnecessarily complicated.

The Game Changer

Top-level await allows you to use await directly at the top level of a module—outside any function. Your module can pause during initialization, wait for a promise to resolve, and then continue, making async setup feel natural and clean.

How It Works

When a module uses top-level await, that module's execution pauses until the awaited promise settles. Any modules importing it will wait too—they won't execute until this module finishes its async work. Think of it like a traffic light: downstream modules wait for the green signal before proceeding.

// config.js - using top-level await
const response = await fetch('/api/config');
const config = await response.json();

export default config;

// main.js - importing waits automatically
import config from './config.js';
// config is already loaded and ready to use
console.log(config.apiKey);

This only works in ES modules (files using import/export), not in scripts or CommonJS.

Why It Matters

Top-level await eliminates boilerplate for module initialization. Instead of complex wrapper patterns, you write straightforward async code right where you need it—at module scope.

Key Takeaway: Top-level await lets you use await outside async functions at a module's top level, making async initialization clean and natural in ES modules.