Interview Q&A · JavaScript · 10 questions in this topic

Modules & Error Handling — JavaScript Interview Q&A

All JavaScript topics

Structuring code — ES modules, imports/exports, exceptions and defensive patterns. Part of Modules & Metaprogramming · 204 questions in the JavaScript bank.

How do ES modules work (import/export)?

Answer

Files are modules (strict, scoped): named exports (multiple, tree-shakeable) plus one default export, imported statically (analyzable) or dynamically (import() for code-splitting). Imports are live read-only bindings — exporter mutations reflect in importers.

Named-for-APIs, default-for-main-entry, dynamic-for-splitting is the usage map.

Example

Example.jsjs
// math.js: export const add = (a, b) => a + b;
// app.js: import { add } from './math.js';
// const { heavy } = await import('./heavy.js'); // lazy split

💡 Live-bindings (not copies) is the deep-cut detail.

What is the difference between CommonJS and ES modules?

Answer

CommonJS (require/module.exports, Node legacy): dynamic, synchronous, value-copies, per-module wrappers. ESM (import/export): static, async-capable, live bindings, tree-shakeable, browser-native. Interop needs care (default-export bridging, __dirname absence).

ESM is the standard path; CJS survives in legacy/dual packages.

Key points

  1. 1CJS — dynamic require, value copies.
  2. 2ESM — static import, live bindings.
  3. 3Interop — default bridging, path helpers.

Example

Example.jsjs
// CJS: const fs = require('fs'); module.exports = {...};
// ESM: import fs from 'fs'; export const x = 1;

How do circular imports behave (and how do you break cycles)?

Answer

ESM tolerates cycles via hoisted live bindings — but reading a not-yet-initialized binding throws (TDZ across modules). Break cycles by extracting shared code to a third module, deferring use to call time, or inverting the dependency.

Third-module-extraction is the structural fix; deferred-use the tactical one.

Example

Example.jsjs
// a.js imports b.js, b.js imports a.js: works ONLY if
// top-level reads happen after both evaluate (function bodies defer)

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits