JavaScript › ES Modules

Why are ES Module imports 'hoisted' and evaluated before the rest of the module's code runs?

Intermediate

Answer

The JS engine statically analyzes all import declarations first and resolves/executes the imported modules before running the importing module's own top-level code, ensuring all bindings are available regardless of where the import statement appears in the file.
console.log(PI); // works even though import is written below
import { PI } from './constants.js';
Real-world example Relying on imported constants or functions being available immediately at the top of a file's execution.

Common follow-ups: Does this mean import order in the file affects behavior?