JavaScript · Senior · Question 35 of 75

What can happen with a circular dependency between ES modules?

// a.js
import { b } from "./b.js";
export const a = "A" + b;
// b.js
import { a } from "./a.js";
export const b = "B" + a;

Explanation

Modules execute in graph order; with a cycle, one of them starts running while the other's export is still in the TDZ. With var you'd get undefined; with const/let/classes, an error. The fix is to move shared code into a third module or access the import lazily inside functions.

Further reading

Problem with a question

JavaScript · Senior · question 35

Test yourself

Take the JavaScript · Senior quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz