Member-only story

Execution order of JavaScript modules

Marian C.
3 min readApr 26, 2021

--

JavaScript modules (also known as ES6 modules) are always executed in the same predefined order.

Left-to-right post-order tree traversal. The nodes are processed in order A C E D B H I G F. The illustration borrowed from https://en.wikibooks.org/wiki/A-level_Computing/AQA/Paper_1/Fundamentals_of_algorithms/Tree_traversal#Post-order

When a module imports other modules, the order in which all the modules are executed is guaranteed to be the same. The order is called left-to-right post-order traversal. Before a module (parent) is executed, all the modules it imports (child modules) are executed. The child modules are executed in the order in which they are specified in the import statements in the parent module. Let’s make several experiments to demonstrate that.

The complete code of the three tests can be downloaded from Github https://github.com/marianc000/executionOrderModules.

Execution order of child modules

For the first demonstration, I create eight identical child modules a, b, c, d, e, f, g, h. Each of them contains only one line of code — a call to global function recordExecution with the module url as an argument (modules can retrieve their urls from module-specific import.meta object).

recordExecution(import.meta.url);

Helper function recordExecution extracts the module name from the url, and appends it to the end of global array exections. recordExecution serves to record a module execution. After all modules are executed, exections array will contain…

--

--

Marian C.
Marian C.

Written by Marian C.

Java, JavaScript and SQL developer. Interested in data collection and visualization.

No responses yet