6 Sneaky JavaScript Patterns to Cut Boilerplate
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 guards:
// 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” file:
// 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 leaks:
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 lib:
const escape = (strings, ...values) => strings.reduce( (acc, str, i) => acc + str + (values[i] ? String(values[i]).replace(/[&<>"']/g, (s) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''', })[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 changes:
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-ins:
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.