6 Sneaky JavaScript Patterns to Cut Boilerplate

Yikun Peng


Micro-optimizations and quality-of-life hacks to keep your scripts lean, readable, and bug-resistant.

1. Optional Chaining ?. + Nullish Coalescing ??

Stop writing five nested guards11: Optional chaining was introduced in ES2020 and has excellent browser support. However, ensure your build tools transpile for older environments if needed.:

// Old
const theme =
  user && user.settings && user.settings.theme ? user.settings.theme : "light";

// New
const theme = user?.settings?.theme ?? "light";

Fewer lines, same safety.


2. Barrel Files for One-Line Imports

Aggregate related exports into a single "barrel" file22: Be careful with barrel files in large projects - they can impact tree-shaking if not configured properly. Modern bundlers like Vite handle this well, but Webpack may require additional optimization.:

// utils/index.js
export * from "./format";
export * from "./validate";
export * from "./fetch";

// SomeComponent.js
import { formatDate, validateEmail, getJSON } from "@/utils";

Kill import clutter without sacrificing tree-shaking.


3. Memoize Pure Functions with a WeakMap

Cache heavy computations tied to objects—no leaks33: WeakMap only accepts objects as keys, not primitives. For caching with primitive values (strings, numbers), use a regular Map but be mindful of memory management.:

const cache = new WeakMap();

export function expensive(obj) {
  if (cache.has(obj)) return cache.get(obj);
  const result = crunchNumbers(obj); // 🚀 costly
  cache.set(obj, result);
  return result;
}

Results follow the object's lifetime—GC does the cleanup.


4. Tagged Template Literals for Safe HTML

Prevent XSS without a third-party lib44: This pattern is great for simple cases, but for complex applications consider using DOMPurify or a framework's built-in sanitization. The escape function shown here only handles basic HTML entities.:

const escape = (strings, ...values) =>
  strings.reduce(
    (acc, str, i) =>
      acc +
      str +
      (values[i]
        ? String(values[i]).replace(
            /[&<>"']/g,
            (s) =>
              ({
                "&": "&amp;",
                "<": "&lt;",
                ">": "&gt;",
                '"': "&quot;",
                "'": "&#39;",
              }[s])
          )
        : ""),
    ""
  );

const name = "<script>alert(1)</script>";
document.body.innerHTML = escape`<p>Hello, ${name}!</p>`;

Zero dependencies, maximum safety.


5. AbortController for Cancellable fetch

Stop orphaning network calls on route changes55: AbortController works with any API that accepts an AbortSignal, not just fetch. You can use it with custom async operations, event listeners (via addEventListener's signal option), and even React Query mutations.:

const controller = new AbortController();
const { signal } = controller;

fetch("/api/data", { signal })
  .then((r) => r.json())
  .catch((e) => {
    if (e.name !== "AbortError") throw e;
  });

// later…
controller.abort();

No more "state update on unmounted component" warnings.


6. Format Like a Native with Intl

Forget custom helpers—use the built-ins66: The Intl API has excellent browser support (IE11+), but older browsers may need polyfills. Consider caching Intl.NumberFormat and Intl.DateTimeFormat instances for better performance when formatting many values, as creating new formatters can be expensive.:

const usd = new Intl.NumberFormat("en-US", {
  style: "currency",
  currency: "USD",
}).format(1999.99); // "$1,999.99"

const isoDate = new Intl.DateTimeFormat("sv-SE").format(new Date());
// "2025-06-05"

Locale-aware, performant, and zero bloat.