Modern JS & TypeScript Cheat Sheet
Quick reference for ES6+ & TypeScript: closures & this, destructuring/spread/structuredClone, ?? vs ?., Event Loop order, async/await + AbortController, unknown vs any, Discriminated Unions, Generics & Utility Types, Event Delegation, and Vitest.
1 min readUpdated 2026-12-01
Scope, Closures & this
javascript
// Regular method keeps `this`; arrow callback inherits enclosing `this`
const tracker = {
prefix: "[LOG]",
items: ["ts", "js"],
print() {
return this.items.map((x) => this.prefix + " " + x);
},
};Immutability, ??, ?. & structuredClone
javascript
const retries = config.retries ?? 3; // Preserves 0 and false!
const deepCopy = structuredClone(nestedState);
const unique = [...new Set(tags)];Event Loop, fetch & AbortController
- Order: Sync Call Stack → ALL Microtasks (
Promise.then,await) → Next Macrotask (setTimeout, DOM events). - Always check
if (!res.ok) throw new Error("HTTP " + res.status);onfetch().
javascript
const controller = new AbortController();
const res = await fetch("/api/search?q=ts", { signal: controller.signal });
// controller.abort() cancels stale in-flight requests!TypeScript Narrowing, Unions & Utility Types
ts
type ApiState<T> =
| { status: "loading" }
| { status: "success"; data: T }
| { status: "error"; message: string };
type PublicUser = Omit<User, "passwordHash">;
type UserPatch = Partial<Pick<User, "name" | "email">>;Event Delegation & XSS-Safe DOM
javascript
listEl.addEventListener("click", (e) => {
const btn = e.target.closest("button[data-action]");
if (!btn) return;
const row = btn.closest("[data-id]");
// Render user text with el.textContent (NEVER innerHTML!)
});