articles / Cheatsheets

Cheatsheets

Quick reference for the things worth keeping at hand. Everything here is plain, modern JavaScript that runs in current browsers and Node without a library, so you can paste any of it straight into a console and watch it work.

These are the patterns that come up daily rather than an exhaustive listing. The aim is to jog your memory on syntax you already understand, not to teach it from scratch; for that, each topic links through to a full article. Copy what you need and move on.

Array methods

The workhorses for moving data through a list. Remember that the first group returns new arrays while the mutating methods change the original in place.

map(fn)        // transform each item -> new array, same length
filter(fn)     // keep items that pass the test -> new array
reduce(fn, x)  // fold to a single value (give a start value)
find(fn)       // first matching item, or undefined
findIndex(fn)  // index of first match, or -1
some(fn)       // true if any item passes
every(fn)      // true if all items pass
includes(v)    // true if the value is present
flat(d)        // flatten nested arrays by depth d
flatMap(fn)    // map then flatten one level

map, filter and reduce return new arrays and leave the original alone. sort, reverse and splice mutate in place.

Promises & async

// sequential (each needs the last)
const a = await getA();
const b = await getB(a);

// parallel (independent work)
const [x, y] = await Promise.all([getX(), getY()]);

// tolerate partial failure
const results = await Promise.allSettled(tasks);

// cancel / timeout
const c = new AbortController();
setTimeout(() => c.abort(), 5000);
await fetch(url, { signal: c.signal });

fetch essentials

const res = await fetch('/api/items', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify(payload)
});
if (!res.ok) throw new Error(res.status); // fetch does NOT throw on 404/500
const data = await res.json();

Devtools, fast

debugger;            // pause here when devtools is open
console.table(rows); // arrays of objects as a grid
console.assert(cond, msg);
// Conditional breakpoint: right-click a line -> add an expression
// Logpoint: log without editing source, no pause

Objects & destructuring

const { id, name = 'Anon' } = user;   // pull fields, with a default
const { address: { city } } = user;   // nested
const [first, ...rest] = items;       // array destructuring
const merged = { ...base, ...overrides }; // shallow merge
const clone  = structuredClone(obj);  // deep clone (modern)
Object.entries(obj).forEach(([k, v]) => {});
Object.fromEntries(pairs);            // pairs -> object

Destructuring with defaults removes most manual existence checks. Spread copies shallowly; reach for structuredClone when you need a genuine deep copy.

Strings & numbers

`Hello, ${name}`              // template literal
str.padStart(2, '0');         // '7' -> '07'
str.replaceAll('a', 'b');     // every occurrence
'  x '.trim();                // strip whitespace
(1234.5).toLocaleString();    // '1,234.5'
Number.parseInt('0xff', 16);  // explicit radix
(0.1 + 0.2).toFixed(2);       // '0.30' (float caution)

Two reminders worth taping to the monitor: parseInt takes a radix, and floating-point math is approximate, so format money as integer cents rather than trusting 0.1 + 0.2.

Dates & time

const now = new Date();
now.toISOString();            // 2026-01-31T09:00:00.000Z
Date.now();                   // ms since epoch (number)
new Date(2026, 0, 31);        // month is 0-indexed (0 = Jan)
d.getTime();                  // ms timestamp
// formatting for humans:
new Intl.DateTimeFormat('en', { dateStyle: 'medium' }).format(d);

The two classic traps: months are zero-indexed, and a bare date string is parsed in the local time zone while an ISO string with a Z is UTC. For anything beyond simple formatting, a focused date library still earns its place.

DOM one-liners

document.querySelector('.item');      // first match
document.querySelectorAll('.item');   // static NodeList
el.closest('button');                 // nearest ancestor match
el.classList.toggle('open');          // add/remove class
el.textContent = value;               // safe text (no HTML parsing)
el.append(child);                     // modern insert
el.dataset.id;                        // reads data-id attribute

Prefer textContent over innerHTML for anything user-supplied, and lean on event delegation rather than wiring a listener to every element.

The single most common mistake in this whole list is assuming fetch throws on a failed response. It does not: a 404 or 500 resolves successfully, so always check res.ok or the status code before trusting the body. Keep that one in mind and most data-fetching bugs disappear.

For deeper explanations, each of these has a full write-up in the articles, and the glossary defines any term here that is unfamiliar.