JavaScript Core Patterns (ES2024+ / Node.js 22+)
Quick Start
constby default,letonly for reassignment, nevervar- Optional chaining
?.and nullish coalescing??over manual null guards - ESM
import/exportexclusively — treatrequireas legacy structuredClone()overJSON.parse(JSON.stringify())node:prefix for all built-in modules:import fs from 'node:fs'
Minimalism Patterns
- Use
?.for nested property access; use??for defaults (not||— it falsely triggers on0,"",false) - Destructure at point of use to reduce intermediate variables and clarify intent
- Use rest parameters
...argsoverarguments; use spread overObject.assignorconcat - Declare private class fields with
#prefix; never use underscore conventions to simulate privacy - Use
usingdeclarations for explicit resource management — resources with[Symbol.dispose]()auto-cleanup on scope exit - Use
await usingfor async resources ([Symbol.asyncDispose]()); eliminates try/finally for streams and connections - Use
DisposableStack/AsyncDisposableStackwhen resource acquisition is conditional or multiple disposables need aggregation
Efficiency Patterns
- Attach event listeners on a parent element (event delegation); use
event.target.closest()to identify source - Batch DOM mutations into a
DocumentFragmentbefore appending to the live DOM - Use
requestAnimationFramefor all visual/DOM updates; never modify DOM insetTimeoutfor animations - Use
requestIdleCallback(orscheduler.postTask({ priority: 'background' })) for non-urgent background work - Use
IntersectionObserverfor lazy loading, infinite scroll, and visibility detection — never poll scroll position - Call
observer.unobserve(el)orobserver.disconnect()when observation is no longer needed - Use
AbortControllerto batch-remove multiple event listeners with a singleabort()call on cleanup - Use
WeakMapto associate metadata with DOM elements; entries auto-clean when elements are garbage-collected
Code Reuse
- Use ESM
import/exportexclusively; use dynamicimport()for code splitting and lazy-loading - Build reusable UI with Web Components (Custom Elements + Shadow DOM + HTML Templates) — framework-agnostic
- Name custom elements in kebab-case with a hyphen (
my-button) to avoid collision with native HTML tags - Use Declarative Shadow DOM (
<template shadowrootmode="open">) for server-rendered Web Components - Use
:hostand CSS custom properties as the theming API for Web Components; keep internal styles encapsulated - Use
Proxyfor cross-cutting concerns (validation, logging, access control) without modifying target objects - Use
Reflectmethods inside Proxy traps to forward default behavior — never re-implement native semantics - Export pure functions and compose them; prefer composition over class inheritance for business logic
Modern JS (ES2024+ / Node.js 22+)
structuredClone()— deep copy with support forDate,Map,Set,ArrayBuffer, circular refsObject.groupBy()/Map.groupBy()— replace reduce-based grouping patternsSetmethods:.union(),.intersection(),.difference(),.symmetricDifference(),.isSubsetOf()- Immutable array methods:
toSorted(),toReversed(),toSpliced(),with()— no source mutation - Iterator helpers:
.map(),.filter(),.take(),.drop(),.toArray()directly on iterators (lazy) Iterator.from(iterable)— create iterator objects from any iterablePromise.withResolvers()— extract resolve/reject without wrapping in a constructor callbackPromise.try(fn)— unify sync and async error handling into a single promise chainRegExp.escape(str)— safely interpolate user input into regular expressions- Import attributes:
import data from './data.json' with { type: 'json' }for type-safe module imports - Temporal API (
Temporal.PlainDate,Temporal.ZonedDateTime,Temporal.Duration): usetemporal-polyfilluntil native support lands
Node.js 22+ Performance Patterns
- Always use
node:prefix:import { readFile } from 'node:fs/promises' - Use
import.meta.dirnameandimport.meta.filenameinstead of__dirname/__filenamein ESM - Use built-in
fetch()for HTTP; combine withAbortControllerfor timeouts and cancellation - Use
--env-file=.envorprocess.loadEnvFile()to load env vars; eliminates thedotenvdependency - Use
--watchfor dev auto-restart instead ofnodemon - Use
node:testrunner for testing; eliminates Jest/Mocha for most projects - Use Web Crypto API (
globalThis.crypto) for cryptographic operations aligned with browser standards - Run TypeScript directly with
node index.ts(strip-types) for scripts and prototyping
DOM Performance
- Batch reads then writes — never interleave reads and writes (forces layout thrashing)
- Use
IntersectionObserverover scroll listeners; useMutationObserverover DOM polling - Use
ResizeObserverto respond to element size changes without window resize listeners - Event delegation on parent containers scales to thousands of dynamic children at zero extra listener cost
- Virtual scrolling for long lists: render only visible items, translate with
transform: translateY - Prefer CSS for animation, container queries,
:has(), and scroll-driven effects over JavaScript equivalents
Testing
- Use
node:testwithdescribe/itblocks; supports nested suites andbefore/afterhooks - Mock with
context.mock.fn()(spy) andcontext.mock.method(obj, 'name')for object methods - Mock timers:
context.mock.timers.enable({ apis: ['setTimeout', 'Date'] }); advance with.tick(ms) - Coverage:
node --test --experimental-test-coverage— nonycorc8needed - Watch mode:
node --test --watchfor rapid feedback - For browser and E2E: Playwright — cross-browser, network interception, screenshot/video
- Property-based testing: fast-check for discovering edge cases in pure functions
- Vitest for projects already using Vite; Jest API-compatible with faster parallel execution
Anti-Patterns
- Never use
var— hoisting bugs and scope leaks thatconst/letprevent - Never use
JSON.parse(JSON.stringify())for deep cloning — usestructuredClone() - Never poll scroll position with
scrolllisteners — useIntersectionObserver - Never import Lodash, Moment.js, jQuery, or RequireJS for new code — native ES2024+ covers core use cases
- Never use
argumentsobject — use rest parameters...argswhich produce a real Array - Never write manual null-check chains — use
?.and?? - Never modify
Object.prototypeor prototypes you do not own — causes naming collisions - Never use
eval()— security risk and performance penalty - Never add individual listeners to thousands of child elements — use event delegation
- Never attach closures referencing large objects to long-lived event listeners without cleanup — memory leak