Modules and error handling
Modules give every file its own private scope and let it share only what it exports, which ends global name clashes. Error handling with try/catch/finally and custom errors keeps one bad input from crashing the whole app.
16.1 The problem: everything is global
- With normal script tags, top-level variables of every file share one global scope.
- sale.js declared its own discount = 10 and overwrote coupon.js's discount = 50.
- Dependencies are hidden, so a wrong script tag order breaks the code.
JavaScript
// coupon.jsvar discount = 50;function applyCoupon(price) { return price - discount;} // sale.jsvar discount = 10; // app.jsconsole.log(applyCoupon(500));Output
49016.2 export and import (ES modules)
- Each module has its own scope: a non-exported const discount is invisible outside the file.
- Named exports: export const / export function; import them inside curly braces.
- export default: the main thing of the file, only one per file; imported without braces.
- Browser: <script type="module">; Vite and Next.js do this for you.
JavaScript
// coupon.jsconst discount = 50; export const MIN_ORDER = 199; export function applyCoupon(price) { return price - discount;} export default function formatPrice(amount) { return `₹${amount}`;}JavaScript
// app.jsimport formatPrice, { applyCoupon } from "./coupon.js";import { discount } from "./sale.js"; console.log(formatPrice(applyCoupon(500)));console.log("Sale discount:", discount);Output
₹450Sale discount: 1016.3 The older style: CommonJS
JavaScript
// coupon.cjsconst discount = 50;function applyCoupon(price) { return price - discount;}module.exports = { applyCoupon }; // app.cjsconst { applyCoupon } = require("./coupon.cjs");console.log(applyCoupon(500));Output
450| Point | CommonJS | ES modules |
|---|---|---|
| Syntax | require() / module.exports | import / export |
| Loading | At runtime (dynamic) | Static, analysed before running |
| Tree shaking | Hard | Yes, unused exports removed |
| Top-level await | No | Yes |
| Where | Older Node projects | Browsers, modern Node, Vite, Next.js |
16.4 Dynamic import: load when needed
- import("./report.js") is called like a function and returns a Promise.
- Heavy code (a report) loads only when the user needs it: code splitting.
- Top-level await is allowed only in ES modules; React lazy loading is built on dynamic import.
JavaScript
console.log("App ready"); async function openReport() { const { buildReport } = await import("./report.js"); console.log(buildReport([1200, 800, 500]));} await openReport();Output
App readyTotal sales: ₹2500- Myth: 5 files importing a module run it 5 times. No: module code runs once on the first import; everyone gets the cached copy.
- That is why config or a DB connection can be shared across the app.
16.5 Error handling: try, catch, finally
- A thrown error stops the script right there: one bad JSON string stops the whole app.
- try: code that can fail; catch (err): runs on an error with the error object.
- finally: always runs, error or not (hide a loader, close a connection).
JavaScript
const saved = '{"name": "Rahul",}'; const user = JSON.parse(saved);console.log("Hello", user.name); console.log("App still running");Output
Uncaught SyntaxError: Expected double-quoted property name in JSON at position 17JavaScript
const saved = '{"name": "Rahul",}'; try { const user = JSON.parse(saved); console.log("Hello", user.name);} catch (err) { console.log("Bad data:", err.name);} finally { console.log("Loader hidden");} console.log("App still running");Output
Bad data: SyntaxErrorLoader hiddenApp still running- Step 1
1.Run the try block
- Step 2
2.Error thrown? -> skip the rest of try, jump to catch(err)
- Step 3
3.No error -> skip catch
- Step 4
4.finally runs in both cases
- Step 5
5.Code after the block keeps running (app did not crash)
16.6 A custom error class
- class ValidationError extends Error: pass the message to super, set name and extra fields.
- In catch, check with instanceof and handle only the errors you know.
- Re-throw unknown errors so they are not hidden.
JavaScript
class ValidationError extends Error { constructor(field, message) { super(message); this.name = "ValidationError"; this.field = field; }} try { throw new ValidationError("phone", "Need 10 digits");} catch (err) { if (err instanceof ValidationError) { console.log(err.field, err.message); } else throw err;}Output
phone Need 10 digits16.7 Checkpoint: try/catch and async callbacks
JavaScript
try { setTimeout(() => { throw new Error("Timer failed"); }, 0);} catch (err) { console.log("Caught:", err.message);}console.log("Done");Output
DoneUncaught Error: Timer failed- The callback runs later (event loop), after try/catch has already finished.
- Put the try/catch inside the callback.
16.8 Common mistakes
- return fetchUser() without await inside try: the function leaves try before the Promise rejects, so the error escapes catch. Use return await.
- Throwing a string instead of an Error object: no stack trace.
- Empty catch blocks that silently swallow errors: at least log or show a message.
- Using var at the top of classic scripts and relying on script tag order.
JavaScript
// Wrong: the error escapes catchasync function loadUser() { try { return fetchUser(); } catch { return "Guest"; }} // Right: Guestasync function loadUser() { try { return await fetchUser(); } catch { return "Guest"; }}16.9 Interview tips
- CommonJS: require/module.exports, loaded at runtime. ESM: static import/export, tree shaking, top-level await, native in browsers.
- Dynamic import() returns a Promise and enables code splitting (React.lazy).
- A module runs once; later imports get the cached instance.
- Prefer named exports; throw Error objects; never leave an empty catch.
- try/catch cannot catch errors thrown later in async callbacks; use await or catch inside the callback.