Modern JavaScript Cheat Sheet

The syntax that replaced the patterns you learned first

A reference for the modern language: optional chaining, nullish coalescing, the newer array methods and the async patterns that go with them.

Beginner 1 min read 19 Entries Version 1.0 Sabir Updated 1
Download PDF Export Markdown Export HTML

Operators worth knowing

Syntax Meaning
a?.b?.c undefined instead of a TypeError on a missing link
fn?.(arg) Call only if fn exists
a ?? b b only when a is null or undefined — 0 and "" survive
a ||= b Assign when falsy
a ??= b Assign only when nullish
const { a, b: c = 1, ...rest } = obj Destructure, rename, default, collect
structuredClone(obj) A real deep clone — handles Dates, Maps and cycles

Arrays

Method Note
arr.at(-1) Last element, without arr.length - 1
arr.toSorted() Sorts a COPY — .sort() mutates in place
arr.toReversed(), arr.toSpliced() The other non-mutating twins
arr.with(0, "x") A copy with one index replaced
arr.findLast(fn) Search from the end
arr.flatMap(fn) Map then flatten one level
Object.groupBy(arr, fn) Group into an object by key

Promise combinators

Combinator Settles when Use for
Promise.all All fulfil, or any rejects All-or-nothing work
Promise.allSettled All settle, however they settle Batch jobs where partial success is fine
Promise.race The first to settle either way Timeouts
Promise.any The first to FULFIL Redundant sources — try several mirrors

Code examples

Non-mutating array work

The newer methods return a copy, so the source array survives — which is what makes them safe in reactive frameworks.

JavaScript arrays.js Download
const users = [
  { name: 'Ada',  score: 91 },
  { name: 'Linus', score: 78 },
  { name: 'Grace', score: 96 },
];

// Copy, not mutate — `users` is untouched
const ranked = users.toSorted((a, b) => b.score - a.score);

const top = ranked.at(0);              // no ranked[ranked.length - 1] dance
const last = ranked.at(-1);

// Group without a reduce()
const byBand = Object.groupBy(users, (u) => (u.score >= 90 ? 'high' : 'rest'));

// Replace one index, immutably
const patched = users.with(1, { ...users[1], score: 80 });

Frequently asked questions

When should I use ?? instead of ||?
Whenever 0, "" or false are valid values. || treats all of them as missing and substitutes your default; ?? only does so for null and undefined.
Why prefer toSorted() over sort()?
sort() mutates the array in place, which in a reactive framework silently edits state you did not mean to touch. toSorted() returns a copy.

Was this cheat sheet useful?

Comments

No comments yet — be the first.

Need a different cheat sheet? Tell us what you would like to see and we will build it — free.
Request a cheat sheet