Primer Β· JS & TS for OO developers

JavaScript & TypeScript Primer
for Object-Oriented Developers

Everything from "why is 0.1 + 0.2 !== 0.3…" to "who owns this Promise's rejection" β€” taught through real patterns you'll meet reviewing PRs in Node/Express, gateway, and cloud-service code. Built for someone whose mental model is Java/C# β€” every section maps JS/TS to the OO concept you already know, then shows where the model breaks and what that means when you review code.

Target: a working developer who can read Java/C#/C++ fluently and wants to review JavaScript/TypeScript pull requests with deep, specific feedback β€” not just "this looks fine".

0% read
01

Types & the Type System

Java is statically typed: every variable has a compile-time type, and the compiler rejects mismatches. TypeScript adds types on top of JavaScript, but the runtime is still the dynamic JS engine. JavaScript itself is dynamically typed: a variable can hold a number now and a string later, and the runtime will happily apply operators to whatever's there (with surprising results).

7 primitive types

string, number, boolean, null, undefined, symbol, bigint β€” plus one reference type: object. No int/double/long split.

Everything else is object

Arrays, functions, dates, regexes, Map/Set, class instances β€” all object at runtime.

TS is a compile-time veneer

tsc erases types; the emitted JS is untyped. "Type safety" in TS is a build-time promise, not a runtime guarantee.

Java ↔ JS/TS concept map

JavaJavaScript / TypeScriptKey difference
int x = 5; long n = 10L;let x = 5; let n = 10n;One number type (IEEE-754 double). Integers beyond 2^53 lose precision; bigint opt-in.
String s = null;let s = null; let u = undefined;Two "nothing" values: null (explicit) and undefined (uninitialised).
List<Integer> listnumber[] or Array<number>Arrays are objects; they can hold mixed types unless TS constrains them.
Map<K,V>Map<K, V>JS Map preserves insertion order, has O(1) get/set, arbitrary keys. Plain object is the trap (see Β§03).
enum Color { RED }const Color = { RED: "red" } as const or TS enumJS has no true enum; TS enum is a compile-time construct with runtime object β€” prefer as const + union.
interface / class implementsinterface / implements (TS)JS classes have extends but no interfaces; TS interfaces are structural, not nominal (see Β§09).

The typeof operator β€” and its lies

typeof "x"; // "string" typeof 5; // "number" typeof null; // "object" ⚠️ historical bug β€” null is a primitive typeof undefined; // "undefined" typeof []; // "object" typeof (() => {}); // "function"

Review trap: typeof x === "object" is true for null, arrays, Dates, and Maps. If a PR uses typeof to distinguish "a real object", it will silently accept null and arrays. The robust checks:

x === null Β· Array.isArray(x) Β· x instanceof Map Β· plain object via Object.prototype.toString.call(x).

TypeScript adds the missing safety β€” but only at compile time

Java
int add(int a, int b) { return a + b; }
// add("x", 2) β†’ compile error
TypeScript
function add(a: number, b: number): number { return a + b; }
// add("x", 2) β†’ TS compile error βœ“
// at runtime it's just `function add(a, b) { return a+b }` β€”
// types are erased, so a JS caller CAN pass "x" (no guard)

The #1 review mental model: TypeScript cannot protect a runtime boundary. Anything parsed from JSON.parse, req.body, fetch() responses, or an env var is any-or-unknown at runtime even if the TS type says otherwise. A PR that casts req.body as User without validating is lying to the compiler β€” the object could have anything in it. This is the single most common "deep" review finding.

βœ… Check yourself β€” Types

1. In a Node API, req.body arrives as JSON. A handler does const u = req.body as User. What's true?

02

Values, Coercion & Equality

Java lets you write "5" + 3 only with an explicit parse; JavaScript coerces operands automatically. Coercion is where a huge class of PR bugs live β€” and where reviewers earn their keep.

The equality minefield

5 == "5"; // true (loose β€” coerces string β†’ number) 5 === "5"; // false (strict β€” no coercion) null == undefined; // true (special case!) null === undefined; // false 0 == false; // true (!!) "" == 0; // true (!!) [] == ""; // true (!!) [] == 0; // true (!!)

Review rule #1: never allow == in new code (except the idiomatic x == null which catches both null and undefined). ESLint's eqeqeq rule exists for exactly this. If you see == in a PR, the author is either new or hiding a coercion bug.

Truthiness β€” not "false means falsy"

In conditionals, JS converts values to booleans. Falsy values: false, 0, -0, "", null, undefined, NaN, 0n. Everything else β€” including "0", [], {}, "false" β€” is truthy.

if (value) { ... } // skips 0, "", null, undefined, NaN β€” often NOT intended if (value !== undefined) { ... } // only skips undefined

Review trap: checking if (!user.age) to mean "no age" will also reject 0-year-olds and treat age: "0" as present while age: 0 is absent. When the domain value can legitimately be 0 or "", the guard must be explicit: user.age === undefined || user.age === null.

Number precision β€” the review classic

0.1 + 0.2 === 0.3; // false! (0.30000000000000004) 9007199254740991 + 1; // 9007199254740992 β€” 2^53 safe-integer limit (Number.MAX_SAFE_INTEGER)
  • Money / currency in JS: never accumulate floats β€” use integer cents (or a decimal library). A PR doing total += price * qty with dollars is a bug at scale.
  • IDs as numbers: if a DB returns a 64-bit integer id as number, it silently loses precision > 2^53. Review call: return as string, or use bigint.
  • Tolerance comparisons: Math.abs(a - b) < Number.EPSILON or round to cents β€” not === on computed floats.

NaN β€” the only value unequal to itself

const r = parseInt("abc"); // NaN r === r // false β€” NaN !== NaN Number.isNaN(r) // true β€” the ONLY reliable check isNaN(r) // true, but isNaN("5") coerces β†’ false. Use Number.isNaN

Review fingerprint: parseInt / parseFloat / +value on user input, followed by arithmetic β€” check the PR validates the result is finite (Number.isFinite) before using it.

03

Data Structures & Mutability

An OO developer's instinct is "objects are like Java references". That instinct mostly holds, but the mutability model and the object-as-map trap will bite.

Primitives are copied; objects are shared (by reference)

Java β€” references copied
List<String> a = new ArrayList<>();
a.add("x");
List<String> b = a;   // same object
b.add("y");          // a sees it too
JavaScript β€” identical behaviour
const a = ["x"];
const b = a;          // same array object
b.push("y");          // a is now ["x","y"] too

The immutable-data habit for review: JS passes references everywhere, and a function that mutates its argument ("side effect") surprises callers. Array.prototype.sort() and reverse() mutate in place; map/filter/reduce/slice return new arrays. Object.assign / spread ...obj are shallow clones β€” nested objects are still shared. A PR that does const copy = {...obj}; copy.items.push(...) thinks it's safe and mutates the original's nested array.

const is not immutability

const x = 1; // x = 2 β†’ TypeError (rebinding refused) const arr = [1]; arr.push(2); // OK! const only forbids REASSIGNMENT, not mutation const frozen = Object.freeze({ a: 1 }); frozen.a = 2; // silently ignored in sloppy mode; throws in strict; STILL shallow β€” nested objects mutable

Review fingerprint: authors who write const everywhere believing it makes state immutable. Object.freeze is shallow and silent; real immutability needs discipline (or immutable libs). When reviewing, check who can mutate shared state rather than whether it was declared const.

Plain object vs Map β€” the dictionary trap

You wantPlain object {}Map
Arbitrary string keys⚠️ prototype pollution: key "__proto__", "constructor", "toString" collide with inherited propsβœ… safe
Non-string keys (numbers, objects)❌ coerced to string (obj[1] and obj["1"] same key)βœ… any key
Insertion ordermostly, but integer-like keys sort firstβœ… guaranteed
CountObject.keys(x).length β€” O(n) allocβœ… map.size O(1)
IterationObject.entries()βœ… for...of map, map.entries()

Prototype pollution is a security issue, not just a style one.
obj[userInput] = value where userInput === "__proto__" can mutate the prototype chain β€” a classic supply-chain/deserialization attack. Reviewers should flag any code that writes into an object using a key derived from untrusted input. Use Map, or Object.create(null), or validate keys against an allow-list.

Destructuring & spread β€” the modern idioms you'll see everywhere

const { name, age, ...rest } = user; // pull fields out; rest = remaining const [first, ...tail] = items; // array destructure const merged = { ...a, ...b }; // shallow merge (b wins) const copy = { ...obj, age: 30 }; // override pattern const { a: renamed } = obj; // rename in destructure const { missing = "default" } = obj; // default only when undefined

Default-value nuance: destructuring defaults apply only when the value is undefined β€” NOT when it's null. const { x = 1 } = { x: null } gives x === null. A PR that assumes "= default catches null" has a latent hole.

04

The Event Loop β€” JS's Single-Threaded Concurrency

Java uses threads: multiple call stacks, preemptive scheduling, shared-memory concurrency. JavaScript has ONE thread (per isolate). Concurrency is achieved by interleaving tasks, not running them in parallel. This is both the biggest mental shift and the source of most async bugs you'll review.

Anatomy
Call stack β€” runs JS to completion; if it's busy, nothing else runs
↑ pushes/pops ↓
Node APIs / Web APIs β€” timers, I/O, fetch, events (handed to the OS/thread pool)
↑ callbacks queued ↓
Task queue (macrotasks) β€” setTimeout, setInterval, I/O callbacks
↑ ↓
Microtask queue β€” Promise .then/.catch/.finally, queueMicrotask (runs FIRST, has priority)

The ordering rule that decides every "what prints first?" question

  1. Run the current call stack to completion.
  2. Drain the entire microtask queue (all promise reactions).
  3. Take ONE macrotask (e.g. a timer). Run it. Go back to 2.
console.log("A"); setTimeout(() => console.log("B"), 0); // macrotask Promise.resolve().then(() => console.log("C")); // microtask console.log("D"); // Output: A, D, C, B (microtask C beats macrotask B β€” even at 0ms)

Why "setTimeout 0 doesn't run immediately": a timer can only fire when the call stack is empty and all microtasks are done. A slow synchronous loop (while / heavy sync work) blocks the entire event loop β€” no timers, no I/O, no promise reactions. This is why blocking the event loop is the #1 performance review finding in Node: a synchronous CPU-heavy chunk in a request handler freezes every concurrent request.

Why is Node "single-threaded" yet fast?

  • I/O (files, sockets, DB) is asynchronous: while a request awaits a DB query, the loop serves other requests. One thread juggles many in-flight operations (an "event-driven" model, not "one thread per connection").
  • The JS thread never waits β€” it queues the continuation and moves on.
  • CPU-heavy work (crypto, compression, native libs) can use a thread pool (libuv), but the JS code itself stays single-threaded.
  • For true parallelism: worker_threads, or the cluster module, or child processes.

Review checklist from this section: β‘  Any synchronous I/O (fs.readFileSync, child_process.execSync, crypto.createHash(...).update(...).digest() big loops) in a request path? β‘‘ Any unbounded Promise.all or timer soup? β‘’ Any code assuming order between a promise chain and a timer?

05

Promises & async/await β€” The Nuances

A promise is a state machine: pending β†’ fulfilled(value) or rejected(reason). Once settled it never changes. Unlike a Java Future (which you can block on), JS promises are push-based: you register callbacks that run when the value is ready β€” and you can attach them after settlement too.

The 4 nuances that decide review findings

NuanceRealityReview impact
Promises are eagernew Promise(exec) runs exec immediately, not when awaitedCreating a promise for a side-effect starts it at creation; a PR that conditionally "awaits" a previously-created promise may have already fired the side effect
Chaining creates a NEW promisep.then(f) returns a fresh promise; p unchangedMultiple .then on the same promise run independently (fan-out) β€” not sequentially
Returning from a .then flattensreturn a value β†’ next .then gets it; return a promise β†’ it's awaited (assimilation)Forgetting to return inside a .then is the most common silent bug β€” the chain proceeds with undefined and sometimes parallel instead of serial
Errors you throw inside async/.then become rejectionsa thrown exception in an async fn == Promise.rejectCatching-swallowing via empty catch {} hides everything; unmatched catch counts as feature

async/await is sugar over promise chains β€” but with a trap

Promise chain
fetchUsers()
  .then(users => fetchPosts(users[0].id))
  .then(posts => posts.length)
  .then(len => console.log(len))
  .catch(err => console.error(err));
async/await (same flow)
async function go() {
  try {
    const users = await fetchUsers();
    const posts = await fetchPosts(users[0].id);
    const len = posts.length;
    console.log(len);
  } catch (err) {
    console.error(err);
  }
}

The serialization trap: two awaits in a row run sequentially β€” the second waits for the first. Parallel-independent awaits are a latency bug (Promise.all fixes it):

const a = await f(); const b = await g(); β€” total time = time(f) + time(g) ⚠️
const [a, b] = await Promise.all([f(), g()]); β€” total time = max(f, g) βœ…

The combinator family β€” pick the right one in review

CombinatorBehaviourFail mode to flag
Promise.allWaits for ALL; if ANY rejects, the whole thing rejects immediatelyOne failing request nukes other (already-resolved) results; no partial results on error
Promise.allSettledWaits for ALL; never rejects; returns {status, value|reason}[]The one to use when you want partial success (bulk APIs, fan-out with per-item error handling)
Promise.raceSettles with the FIRST settled result (value or error)Timeouts use it: Promise.race([fetch(), timeout(5000)]) β€” but the loser still runs (side effects!)
Promise.anyFirst FULFILLED; rejects only if ALL rejectGreat for "try any replica"; errors aggregated (AggregateError)

Awaiting in loops β€” microtask-batching traps

// SERIAL β€” slow, but correct order: for (const id of ids) { const r = await fetch(id); } // sequential, time = Ξ£ // PARALLEL β€” fast, but fires all at once: const rs = await Promise.all(ids.map(id => fetch(id))); // no concurrency cap β€” 10k ids = 10k sockets ⚠️ // N-capped parallelism β€” the pattern pros use: for (let i = 0; i < ids.length; i += N) { await Promise.all(ids.slice(i, i + N).map(fetch)); }

Review fingerprints here: β‘  await in a loop that could be Promise.all (latency); β‘‘ unbounded Promise.all over user-sized arrays (resource exhaustion / rate-limit); β‘’ using .forEach with async β€” forEach does NOT await; the promises just fire and errors become unhandled rejections (see Β§06).

βœ… Check yourself β€” Promises

1. What does this log, in order?

Promise.resolve().then(() => console.log(1));
setTimeout(() => console.log(2), 0);
console.log(3);

2. A PR has items.forEach(async (it) => await save(it)) followed by console.log("done"). What's the bug?

06

Async Error Handling β€” Where Exceptions Escape

In Java, an exception bubbles up the call stack automatically. In JS, an error thrown inside an async function or a promise callback does not bubble through the call stack β€” it becomes a rejection that must be handled by another promise's catch. If nothing catches it, you get an unhandledRejection β€” process warning (and in newer Node, a crash).

The three error-handling shapes, and how to review them

// 1. try/catch around await (correct) try { const r = await risky(); } catch (e) { handle(e); } // 2. .catch on a chain (correct) risky().then(ok).catch(err => handle(err)); // 3. the silent killer β€” fire-and-forget with no catch: risky(); // rejected promise nobody handles β†’ unhandledRejection queueMicrotask(risky); // same danger

Review rules for async errors

  • A promise must be either awaited or caught, eventually. Any fn() call that returns a promise without await/.catch is a latent unhandled rejection. (Node β‰₯15 crashes the process by default on unhandledRejection β€” that's a production outage, not a warning.)
  • Node/Express specifics: an async route handler that throws does NOT hit the default error middleware automatically (pre-Express 5). A PR adding async (req,res) => { ... } handlers without a wrapper (asyncHandler/express-async-errors) leaves 500s as unhandled rejections. Classic review finding.
  • Swallowing is a bug too: catch (e) {} empty, or catch { log(e) } then continuing as if success, hides the failure from the caller. Every catch should either rethrow, translate, or return a typed failure β€” not vanish.
  • Error types carry shape: fetch rejects on network error but resolves on HTTP 404/500 β€” you must check res.ok. A PR that assumes try { const r = await fetch(url) } catch handles bad status is wrong; res.ok must be checked.
  • Timeout hygiene: AbortController/AbortSignal.timeout(ms) is the modern way; a raw setTimeout "timeout" that doesn't abort leaves the request in flight forever.

Express 4 vs 5: Express 5 (and 4.20+) propagate async errors to the error middleware automatically; Express 4.19 and below do NOT. When you see async handlers, check which Express is in package.json and whether errors are wrapped. This is both a correctness and a security finding (unhandled rejection can take the process down on Node β‰₯15).

07

Prototypes vs Classes β€” "Classes" Are Sugar

Java classes are compile-time blueprints with inheritance. JS uses prototypal inheritance: every object has a hidden [[Prototype]] link, and property lookup walks the chain. Since ES6, class syntax exists, but it's syntactic sugar over prototypes β€” there is no real class system, no private-by-default, no true multiple inheritance.

Java β€” class blueprint
public class Animal {
    protected String name;
    public Animal(String name) { this.name = name; }
    public String speak() { return "..."; }
}
JavaScript β€” class sugar over prototypes
class Animal {
  constructor(name) { this.name = name; }
  speak() { return "..."; }
}
// desugars to: Animal.prototype.speak = function...
// instances link to Animal.prototype via [[Prototype]]

What this means for reviewers

  • "Private" is not a thing by default. #privateField (ES2022) is real privacy; leading-underscore _field is a convention only. A PR relying on underscore "private" is exposing state to any caller.
  • Method binding: methods are NOT bound to the instance. const f = obj.method loses this; you need obj.method.bind(obj) or arrow-field method = () => .... Passing an unbound method (e.g. to an event listener or setTimeout) is a classic this === undefined bug.
  • extends is prototype-chain sugar: class B extends A sets B.prototype.[[Prototype]] = A.prototype. super() must be called before touching this in a subclass constructor.
  • instanceof walks the chain β€” x instanceof Array is true for arrays from the same realm only; across realms (iframes, workers, some Node modules) use Array.isArray.
  • Prototype pollution (again, security): merging untrusted objects into prototypes (Object.assign(target, userObj) where target could be polluted) enables property injection. Validate keys.

The modern-review stance: most new JS code is written with functions + closures or classes-lite, not deep inheritance hierarchies. Deep class A extends B extends C is often an OO habit ported over and usually a smell in JS β€” composition (objects holding objects) and small focused modules read better. When reviewing, ask "is the inheritance buying anything, or is it Java habit?"

08

Scope, this & Closures

Java has block-based lexical scoping too, but JS adds three things that change everything: function hoisting, closures over mutable variables, and a dynamic this (unlike Java's instance-bound this).

The closure-in-loop bug β€” a review rite of passage

// BUG β€” every callback sees the FINAL i for (var i = 0; i < 3; i++) { setTimeout(() => console.log(i), 100); // 3, 3, 3 } // FIX 1 β€” let (block scope per iteration): for (let i = 0; i < 3; i++) { ... } // 0, 1, 2 // FIX 2 β€” capture into a parameter: for (let i = 0; i < 3; i++) { setTimeout(((j) => () => console.log(j))(i)), 100); }

Why it's also a data bug, not just a "loop thing": the same closure-shared-late-binding bites closures over anything captured by reference β€” a reducer reading a config loaded later, an event handler reading a mutable counter. In review: any callback capturing a var or loop variable, or reading outer mutable state at fire-time instead of capture-time, deserves a comment.

this β€” dynamic, unless arrow

FormWhat this is
Regular function function f() {}Determined by call site: obj.f() β†’ obj; f() β†’ undefined (strict) / global
obj.f.call(x)/.apply(x)/.bind(x)Explicitly set
Arrow function () => {}Lexical β€” inherits this from the enclosing scope; cannot be rebound
Class methodSame dynamic rules β€” not auto-bound to the instance (see Β§07)

Closures are memory-bearing β€” watch for leaks

  • A closure keeps its enclosing variables alive as long as the closure itself is reachable. Event listeners / timers / subscriptions holding references to large objects are a real leak vector in long-running Node processes.
  • setInterval holding a closure over a growing array, or a callback registered on a global emitter that keeps the instance alive β€” reviewers should ask "who releases this?" for every long-lived callback.
  • Pattern to praise: setInterval(...); ... clearInterval(...) on shutdown; emitter.removeListener / AbortController.abort() at cleanup.
09

Modules β€” CJS vs ESM

Java packages are mostly a namespacing tool. JS modules are a loading, dependency, and execution model β€” and the language is mid-transition between two incompatible systems. You will review both.

CommonJS (require) β€” Node's classic

// exporting module.exports = { chunk, merge }; exports.chunk = chunk; // alias of module.exports β€” reassigning module.exports breaks it ⚠️ // importing β€” synchronous, cached, evaluated once const { chunk } = require("./lib/pack");
  • require is synchronous and cached: the module runs once; every require reuses the same instance. Objects exported are shared β€” mutating an exported object mutates it for every importer (surprising for Java devs who expect copies).
  • Circular requires: Node resolves them with partially-initialised modules (the classic trap is requiring a module from its own cycle before it's finished exporting β€” you get undefined).

ESM (import/export) β€” the standard

// exporting export const chunk = ...; // named export default pack; // default // importing import { chunk } from "./pack.js"; // named import pack from "./pack.js"; // default import * as ns from "./pack.js"; // namespace
  • ESM is static and async-loaded: imports are hoisted, and the module graph is resolved before any code runs (enables tree-shaking).
  • Live bindings: import { x } reads the current value of x when used, not a snapshot. (Different from CJS's value-at-require.)
  • Node ESM requires explicit file extensions in relative imports ("./x.js" β€” not "./x"); CJS allows extensionless. A PR mixing the two systems (or a CJS package using __dirname / require inside an ESM file) is a bug to flag β€” __dirname doesn't exist in ESM (use import.meta.url).

Review fingerprint: "type": "module" in package.json vs require(...) usages; __dirname in an ESM file; module.exports mixed with export; and the dual-package hazard (a package loaded as both CJS and ESM gets two separate instances β€” instanceof and singleton state break).

10

TypeScript: Structural Typing & the Safety Model

Java types are nominal: two classes with identical fields are different types unless they share a name / inheritance. TypeScript is structural: any object that shapes like the type is assignable to it. This is the single biggest "wait, that compiles?!" surprise for OO devs.

Java β€” nominal
class Point { int x, y; }
class Pixel { int x, y; }
Point p = new Pixel();  // βœ— compile error β€” names differ
TypeScript β€” structural
interface Point { x: number; y: number }
interface Pixel { x: number; y: number }
const p: Point = getPixel();  // βœ“ compiles if shapes match

What structural typing means in review

  • Excess property checking is a lie for variables: assigning a literal object checks for extra properties, but assigning a variable of a wider type does not. const a: A = {x:1, extra:2} errors; const b = {x:1, extra:2}; const a: A = b compiles. Reviews should not trust "TS will reject wrong-shaped data" at runtime boundaries.
  • It enables great minimal interfaces: functions should declare the narrowest shape they need ({ id: string }), letting any wider object in. That's idiomatic and good β€” but only when the caller actually has the fields (see runtime-validation rule Β§01).
  • Discriminated unions are the flagship pattern (see Β§11) β€” replacing Java's instanceof-tree with a single kind/type field and exhaustive narrowing.

any, unknown, never β€” the power trio

TypeMeaningReview stance
anyOpt out of checking entirely β€” assignable to/from everythingπŸ”΄ Flag. any spreads: a variable typed any voids the safety of everything it touches. Exceptions: legacy interop, truly dynamic data you validate immediately after.
unknown"I don't know" β€” must narrow before useβœ… Prefer at boundaries: JSON.parse β†’ unknown, then validate/narrow to a real type. Forces the runtime check TS can't do.
neverUninhabited β€” no value has this typeβœ… Harness for exhaustiveness: the final else/default branch typed never fails to compile if someone adds a union member and forgets it. Reviewers love seeing it.

Review rules that matter more than style: β‘  strict: true in tsconfig is non-negotiable for new code (strictNullChecks alone eliminates the most common JS crash: reading a property of undefined). β‘‘ Disallow as casts on unvalidated runtime data. β‘’ Watch for @ts-ignore / any sprinkled to "make it compile" β€” each is a hole. β‘£ as any is almost always a bug signal, not a workaround.

interface vs type β€” and what changes for review

interfacetype alias
Mergeableβœ… declaration merging (augment)❌ no
Unions / intersections / primitives / mapped types❌ noβœ… yes
Extendsinterface B extends Atype B = A & {...}
Performance edgeslightly faster to typecheck (cache)marginal

Rule of thumb you'll see in guides and should echo in reviews: use interface for public object shapes you'll extend or merge; use type for unions, intersections, tuples, and computed types. Either works 95% of the time β€” consistency matters more than the choice.

11

TypeScript: Advanced Patterns You'll Actually See

Discriminated unions + exhaustiveness β€” the review gold standard

type Result = | { kind: "ok"; value: number } | { kind: "err"; message: string }; function handle(r: Result): string { switch (r.kind) { case "ok": return `value ${r.value}`; case "err": return `error ${r.message}`; default: { const _exhaustive: never = r; // compile error if a new kind is added return _exhaustive; } } }

Why reviewers love this: it's the type-safe replacement for Java's exception-trees/instanceof-chains, it makes invalid states unrepresentable (a Result can't be both ok and err), and the never default catches future drift at compile time. Praise it when you see it; suggest it when a PR uses boolean flags or parallel arrays to model alternatives.

Type narrowing β€” the "smart" checks

function len(x: string | string[]): number { if (typeof x === "string") return x.length; // narrowed to string return x.length; // narrowed to string[] } // also: Array.isArray(x), x instanceof Foo, 'field' in obj, // truthiness narrowing (!x), user-defined type guards (x is Foo)

Generics β€” constraint + infer

function first<T>(arr: T[]): T | undefined { return arr[0]; } // generic with a constraint: function save<T extends { id: string }>(entity: T): T { ... } // conditional/inference utilities you'll see in libs: type Unwrap<T> = T extends Promise<infer U> ? U : T; // Promise<number> β†’ number

Utility types to know before reviewing: Partial<T>, Required<T>, Readonly<T>, Pick<T,K>, Omit<T,K>, Record<K,V>, ReturnType<F>, Awaited<T>, NonNullable<T>, Exclude/Extract, Parameters<F>. A PR using any where Pick/Omit/Record fits is missing the point.

satisfies, as const, and enum β€” three things to check

  • as const turns a literal object into readonly literal types β€” the idiomatic "enum substitute": const Roles = { ADMIN: "admin", USER: "user" } as const gives you type Role = (typeof Roles)[keyof typeof Roles].
  • satisfies checks a value against a type without widening it: const cfg = {...} satisfies Config keeps the literal types while verifying the shape.
  • TS enum is a runtime object with reverse mappings and is a source of "enum vs union" debates; numeric enums especially can be a footgun. In review: prefer as const + union unless the codebase standardises on enums.
12

JS/TS Code Review Playbook

Now the part you actually asked for: where to look, in what order, and how to phrase feedback with depth. The drills below are built from the exact bug classes in this primer β€” subtle enough that they routinely ship merged.

The reviewer's rubric for JS/TS

LensAsk yourself
Runtime boundariesAnything parsed (JSON, req.body, env vars, fetch responses, DB rows) validated before use? Any as T cast on unvalidated data? any leaking?
Async correctnessEvery promise awaited or caught? Async in forEach? Serial awaits that should be Promise.all? Unbounded parallelism? unhandledRejection risk?
Error handlingEmpty/vanishing catches? res.ok checked after fetch? Express async handlers wrapped? Errors leaking internals to clients?
Data semantics== anywhere? Truthiness used where 0/"" are valid? Float money math? 2^53 ids as numbers? sort() mutating shared arrays? Shallow-clone-treated-as-deep?
State & scopeClosures capturing loop vars/late-bound state? Unbound methods losing this? Listeners/timers never cleaned up? Module-level mutable state shared across requests?
Security surfacePrototype pollution from untrusted keys? Secrets in logs/env committed? Input length limits? Regex DoS (ReDoS) on user input? PII in logs?
TypeScript honestyDoes the type system prove the claim, or are the seams papered with any/@ts-ignore/as? Exhaustive switches? strict on?
SystemicSync I/O on the event loop? Module-system confusion (CJS/ESM)? Node version assumptions? Dependency with known CVEs (npm audit)? Over-broad dependency (lodash for one fn)?

How to use the drills: read the snippet, form your own hypothesis before answering, then check. The analysis goes deeper than the multiple-choice β€” root cause β†’ blast radius β†’ concrete fix β†’ the exact phrasing to use in review.

Drill 1 Β· Severity: HIGH

Parallel awaits, serialized

async

Context: An Express handler that enriches a user record before responding.

async function getUserWithEnrichments(id) { const user = await db.getUser(id); const posts = await db.getPosts(user.id); // independent β€” but runs after user const subs = await db.getSubscriptions(user.id); // independent β€” runs after posts return { user, posts, subs }; }

What's the real issue, aside from style?

Root cause

Confusing "async = automatic concurrency" with "await = I'm waiting, but the loop can go do other requests". await suspends THIS function; it does not run other awaits in parallel.

Blast radius
  • Latency: total = t_user + t_posts + t_subs; correct = t_user + max(t_posts, t_subs).
  • At scale: longer-held DB connections per request β†’ fewer concurrent requests served β†’ queueing.
  • Easier to miss when the calls are hidden inside helpers: await a(); await b() in different lines reads innocent.
Fix pattern
const [posts, subs] = await Promise.all([ db.getPosts(user.id), db.getSubscriptions(user.id), ]);

Parallelism is explicit in JS β€” reviewers should treat adjacent independent awaits as a finding, not a nit, when latency matters.

Review phrasing: "These two awaits are independent β€” they only need user.id. Running them serially adds a full DB round-trip to every request. `Promise.all` makes it max() instead of sum()."
Drill 2 Β· Severity: CRITICAL

The async handler with no catch

reliability

Context: Express 4 app. New endpoint added with an async handler.

app.post("/api/orders", async (req, res) => { const order = await createOrder(req.body); // if this rejects… res.status(201).json(order); });

The DB write fails. What actually happens?

Root cause

Express 4's handler contract is synchronous. An async handler returns a Promise the framework ignores; rejection = unhandled.

Blast radius
  • Client hangs (no response) β†’ LB timeout β†’ retry storms.
  • Node β‰₯15 default: crash on unhandledRejection β†’ whole process, all users.
  • Errors invisible in logs (no middleware ran) β†’ hard to diagnose.
Fix pattern
// wrap: const asyncHandler = (fn) => (req, res, next) => Promise.resolve(fn(req, res, next)).catch(next); app.post("/api/orders", asyncHandler(async (req, res) => { const order = await createOrder(req.body); res.status(201).json(order); })); // or upgrade to Express 5 (async errors propagate), or use express-async-errors
Review phrasing: "This async handler's rejection is never caught β€” Express 4 won't send a 500, the request hangs, and if createOrder rejects we hit unhandledRejection (a crash on modern Node). Wrap it or upgrade Express."
Drill 3 Β· Severity: HIGH

The truthiness gate that eats zero

data semantics

Context: A session/cost API. Each session has a budgetUsd that may legitimately be 0 (free tier, test tenant).

function applyPolicy(session) { if (!session.budgetUsd) { // "no budget" check return { allow: false, reason: "no budget configured" }; } // …cost check… }

What breaks?

Root cause

Using truthiness as a presence check. if (!x) means "x is falsy" β€” which includes 0, "", NaN, false β€” not "x is absent".

Blast radius
  • Free-tier tenants (0 budget) blocked; empty-string configs treated as defaults; falsy-but-valid flags flipped.
  • Usually discovered in prod by a specific class of user β€” 0-count, 0-price, ""-value β€” i.e. exactly the users with the most sensitive edge cases.
Fix pattern
if (session.budgetUsd === undefined || session.budgetUsd === null) { return { allow: false, reason: "no budget configured" }; }
Review phrasing: "This presence check rejects legit 0 values. Use an explicit undefined/null check (or a hasOwnProperty/optional-field pattern) so a zero budget is a real budget."
Drill 4 Β· Severity: HIGH

The shallow copy that mutated the original

data integrity

Context: An in-memory cache + audit helper.

const cached = { items: ["a"], meta: { count: 1 } }; function addOne(entry) { const copy = { ...entry }; // "copies" the object… copy.items.push("b"); // …but items is SHARED with entry copy.meta.count += 1; // mutates the ORIGINAL's nested meta return copy; }

The caller's cached object β€” what changed?

Root cause

Shallow-copy semantics mistaken for deep-copy. Applies to Object.assign and spread alike; also applies to JSON.parse(JSON.stringify(x)) in reverse (deep but drops functions/Date/undefined and can throw on cycles).

Blast radius
  • Cache corruption: the "copy path" writes into the shared cached object β†’ every subsequent read sees the mutation.
  • Hard to spot: the bug lives in a helper far from both call sites.
  • Multi-request shared state (module-level cache) makes it a concurrency-visible bug: one request's transform leaks into another's view.
Fix pattern
const copy = { ...entry, items: [...entry.items], meta: { ...entry.meta } }; // or structural clone: structuredClone(entry) β€” deep, handles Dates/Maps, Node 17+ // or library (lodash cloneDeep) for exotic structures
Review phrasing: "This 'copy' shares its nested arrays/objects with the source. Mutations write through. Either clone the nested levels explicitly (or structuredClone) or treat the object as immutable and rebuild it."
Drill 5 Β· Severity: HIGH

Typed lie at the API boundary

TypeScript honesty

Context: TypeScript service; request body handled without validation.

interface Charge { amountCents: number; currency: string; } app.post("/charge", async (req, res) => { const charge = req.body as Charge; // "trust me" const total = charge.amountCents * 100; // if amountCents is "abc" β†’ NaN, or missing β†’ undefined*100 β†’ NaN res.json({ total }); });

What's the right review call?

Root cause

Treating the type system as a runtime validation layer. TS erases types; req.body is whatever the client sent.

Blast radius
  • NaN stored to DB (bad data at rest), 500s on missing fields, and β€” worse β€” security checks gated on typed-but-unvalidated fields (e.g. role cast to AdminRole) can be bypassed with crafted JSON.
  • The compile-time ecosystem gives false confidence; the bug class is identical to "magic from JSON in Java without parsing".
Fix pattern
// 1. change the cast target to unknown, 2. validate: import { z } from "zod"; const ChargeSchema = z.object({ amountCents: z.number(), currency: z.string() }); const charge = ChargeSchema.parse(req.body); // throws / returns typed+validated
Review phrasing: "This `as Charge` cast trusts unvalidated client JSON. `amountCents` may be missing/string/null β€” the math goes NaN and downstream writes get corrupted. Validate at the boundary (zod or manual guards)."
Drill 6 Β· Severity: MEDIUM

sort() mutating shared state

data integrity

Context: A list endpoint reused per request; results cached in a module-level array.

const cachedProducts = loadOnce(); app.get("/products?sort=price", (req, res) => { const list = cachedProducts; // same array reference every request if (req.query.sort) list.sort((a, b) => a.price - b.price); // in-place! res.json(list); });

What's the hidden consequence?

Root cause

Thinking sort returns a new array (like map). It mutates + returns the same reference.

Blast radius
  • One request's sort option permanently changes the cached ordering for all users β€” subtle, data-dependent, near-impossible to reproduce deterministically.
  • Same class: reverse(), splice(), push/pop/shift/unshift, fill(), and object mutation via helpers.
Fix pattern
const list = [...cachedProducts].sort((a, b) => a.price - b.price); // copy, then sort
Review phrasing: "sort() mutates the shared cached array in place β€” one request reorders it for everyone. Copy first (`[...arr].sort(...)`) or keep the cache immutable and return derived arrays."
13

Glossary β€” the terms reviewers actually use

Coercion

Implicit type conversion when operators meet mismatched types ("5" + 3 β†’ "53", "5" - 3 β†’ 2). The + operator concatenates if either operand is a string; other arithmetic operators convert to numbers.

Falsy / truthy

Values that coerce to false/true in boolean contexts. Falsy: false, 0, -0, "", null, undefined, NaN, 0n.

Event loop

The single-threaded scheduling loop that interleaves synchronous code, microtasks (promise reactions) and macrotasks (timers, I/O). Order: call-stack β†’ all microtasks β†’ one macrotask β†’ repeat.

Microtask vs macrotask

Microtasks (promise callbacks, queueMicrotask) drain before macrotasks (setTimeout/setInterval, I/O). Why Promise.resolve().then(...) beats setTimeout(0).

Rejection

A promise settled with a reason (error). Not an exception; it's a value flowing down the chain. Unhandled rejections crash modern Node.

Unhandled rejection

A rejected promise with no .catch/await. Node β‰₯15 exits by default β€” a production outage vector.

Prototype chain / [[Prototype]]

The hidden link objects use for property resolution. Class extends sets it; hasOwnProperty distinguishes own vs inherited.

Closure

A function retaining access to its enclosing scope's variables after that scope exits. The mechanism behind callbacks, and the source of capture-vs-reference bugs.

Hoisting

var and function declarations are moved to the top of their scope. var is function-scoped and hoisted-but-undefined; let/const are block-scoped with a temporal dead zone. Why "always use let/const".

TDZ (temporal dead zone)

The window where a let/const binding exists but isn't initialised β€” accessing it throws ReferenceError.

Shallow vs deep copy

Shallow (spread, Object.assign) copies top-level references; deep (structuredClone, JSON round-trip with caveats) copies nested values.

Prototype pollution

Writing into __proto__/constructor.prototype via untrusted keys can modify the shared prototype chain β€” a security vulnerability class.

Strict mode

"use strict" (or ESM/modules, which are always strict) β€” disables sloppy-mode footguns (silent failures become throws, this in plain calls is undefined).

Structural typing

TypeScript's rule: assignability by shape, not name. Enables minimal interfaces; requires runtime validation at real boundaries.

Type narrowing

TS refining a union to a specific member inside a branch (typeof, instanceof, in, discriminated kind, type guards).

Discriminated union

A union of object types sharing a literal tag field (kind); narrowing on the tag gives exhaustive, type-safe alternatives.

satisfies

TS operator that checks a value against a type without widening the literal types β€” "shapes like, but stays precise".

as const

Marks a literal as readonly and gives literal types β€” the idiomatic enum replacement.

CommonJS vs ESM

Two module systems: require/module.exports (synchronous, cached, Node-classic) vs import/export (static, async, standard). Mixing them breaks __dirname, require, and can duplicate module state.

Tree shaking

Bundlers dropping unused exports at build time β€” enabled by ESM's static analysis. Why "import { chunk } from 'lodash-es'" beats importing the whole lodash.

AbortController / AbortSignal

The modern way to cancel fetch and timeouts; AbortSignal.timeout(ms) is a one-liner timeout that actually aborts the request.

NaN

"Not a Number" β€” result of failed numeric coercion. The only value !== itself; check with Number.isNaN.

ReDoS

Regular-expression denial of service: a catastrophic-backtracking regex run over user input can lock the single event loop thread. Review user-input regexes for nested quantifiers.