Interview Q&A · JavaScript · 10 questions in this topic
Modules & Error Handling — JavaScript Interview Q&A
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
// 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
- 1CJS — dynamic require, value copies.
- 2ESM — static import, live bindings.
- 3Interop — default bridging, path helpers.
Example
// 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
// a.js imports b.js, b.js imports a.js: works ONLY if // top-level reads happen after both evaluate (function bodies defer)
How do try/catch/finally and throw work?
Answer
try guards risky code; catch receives the thrown value (unknown-typed — narrow before use); finally always runs (cleanup, regardless of outcome); throw raises anything (Error instances carry stack/message). Async errors need await-in-try or .catch — sync try cannot catch async rejections.
Narrow-unknowns-in-catch is the TypeScript-era discipline.
Example
try { JSON.parse(maybeBad); } catch (e) { if (e instanceof SyntaxError) fallback(); else throw e; // rethrow unknowns } finally { cleanup(); }
💡 Rethrow-what-you-don't-handle is the catch hygiene rule.
What are `Error` types (and how do you create custom errors)?
Answer
Built-ins: Error (base), TypeError, RangeError, ReferenceError, SyntaxError, AggregateError (any/all rejections). Custom errors extend Error (name set, stack captured, cause chaining via { cause }). instanceof narrows handlers.
Cause-chaining preserves root context across layers.
Example
class HttpError extends Error { constructor(status, msg, opts) { super(msg, opts); // { cause } chains this.name = 'HttpError'; this.status = status; } }
How do you handle promise rejections globally (safety nets)?
Answer
unhandledrejection (browser) and unhandledRejection (Node) catch missed rejections — log-and-alert backstops, never primary logic (which belongs in local catch). Node may crash on unhandled rejections by default — design for zero.
Local-catch-primary, global-hook-backstop is the layered doctrine.
Example
window.addEventListener('unhandledrejection', (e) => { report(e.reason); // backstop only });
💡 Zero-unhandled-in-CI is the enforceable standard.
What is defensive coding at API boundaries (validation, defaults)?
Answer
Validate inputs where trust ends (network, storage, user): schema checks (zod), defaults via destructuring/??, early-throw on contract violation, and normalized outputs. Fail fast with clear errors beats deep silent corruption.
Trust-ends-here is where validation lives.
Example
function createUser({ name, age = 0 } = {}) { if (typeof name !== 'string' || !name) throw new TypeError('name?'); }
What is 'use strict' and is it still needed?
Answer
Strict mode bans silent hazards (implicit globals, duplicate params, with-statement, this-boxing) turning them into errors. Modules and classes are strict by default — explicit directives survive in classic scripts and legacy bundles.
Modules-made-it-default is why new code rarely writes it.
Example
// 'use strict'; // classic scripts only; modules: automaticHow do you structure a small library (exports, entry, side effects)?
Answer
Named exports per capability, documented default/main entry, package.json exports map (subpaths, types, sideEffects flags for tree-shaking), zero top-level side effects on import. Consumers pay only for imports used.
Side-effect-free-imports is the tree-shaking contract.
Example
// package.json: { "exports": { ".": "./index.js" }, // "sideEffects": false }
💡 sideEffects-false is the bundler handshake to name.
How do source maps work (and should they ship to production)?
Answer
Source maps map minified code back to sources for debugging (stack traces, devtools). Ship them when debugging production matters with access control (private servers, Sentry-style upload — never public alongside secrets); omit for minimal exposure.
M folklore: maps don't weaken minification's size win — only its obscurity.
Example
// //# sourceMappingURL=app.js.map💡 Access-controlled-maps is the balanced policy.
Recommended resourcesAffiliate links · may earn us a commission