JavaScript Cheat Sheet
Modern JavaScript syntax and methods at a glance.
Variables and types
const x = 1Block-scoped constant binding
let y = 2Block-scoped variable
typeof valueType name: "string", "number", "object", "undefined" ...
Number.isInteger(n)Check for an integer
value ?? fallbackNullish coalescing: fallback only for null / undefined
obj?.a?.bOptional chaining: undefined instead of a TypeError
a ||= b, a &&= b, a ??= bLogical assignment operators
Strings
`Hi ${name}`Template literal with interpolation
s.includes("a") / startsWith / endsWithSubstring checks
s.slice(1, 4)Substring by index (negative counts from the end)
s.split(",") / arr.join(",")String to array and back
s.replaceAll("a", "b")Replace every occurrence
s.trim() / padStart(5, "0")Trim whitespace / pad to length
s.at(-1)Last character
Arrays
arr.map(fn)New array with fn applied to each item
arr.filter(fn)New array with items where fn is truthy
arr.reduce((acc, x) => acc + x, 0)Fold an array into one value
arr.find(fn) / findIndex(fn)First matching item / its index
arr.some(fn) / every(fn)Any / all items match
arr.includes(x)Contains the value
arr.flat() / flatMap(fn)Flatten one level / map then flatten
[...a, ...b]Spread to concatenate or copy
arr.toSorted((a, b) => a - b)Sorted copy (does not mutate)
Array.from({ length: 3 }, (_, i) => i)Build [0, 1, 2]
Objects
const { a, b = 1 } = objDestructuring with default
{ ...obj, a: 2 }Copy with an override
Object.keys / values / entries(obj)Own enumerable keys / values / pairs
Object.fromEntries(pairs)Pairs back to an object
structuredClone(obj)Deep copy
key in obj / obj.hasOwnProperty(key)Property checks
{ [key]: value }Computed property name
Functions
const f = (a, b) => a + bArrow function
function f(a, b = 2, ...rest) {}Default and rest parameters
fn.call(ctx, a) / apply / bindControl the value of this
(() => { ... })()Immediately invoked function expression
function* gen() { yield 1 }Generator function
Async and promises
async function f() { await p }Pause until a promise settles
p.then(ok).catch(err).finally(fn)Promise chaining
Promise.all([p1, p2])Wait for all; rejects on the first failure
Promise.allSettled([p1, p2])Wait for all and get each outcome
Promise.race([p1, p2])First promise to settle
await fetch(url).then(r => r.json())Fetch JSON
setTimeout(fn, 500) / clearTimeout(id)Run once after a delay
DOM
document.querySelector(sel)First match
document.querySelectorAll(sel)NodeList of all matches
el.classList.add / remove / toggleChange classes
el.addEventListener("click", fn)Attach an event listener
el.dataset.idRead data-id
el.textContent = "Hi"Set text safely (no HTML parsing)
localStorage.setItem(k, v)Persist a string in the browser
Classes and modules
class A extends B { constructor() { super() } }Class with inheritance
static x = 1; #private = 2Static and private fields
import x, { y } from "./m.js"ES module import
export default x; export const y = 1ES module exports
try { } catch (e) { } finally { }Error handling
JavaScript Cheat Sheet
This JavaScript cheat sheet focuses on modern syntax (ES2015 and later) that you use every day: declaring variables, working with strings, arrays and objects, writing functions, handling asynchronous code, and touching the DOM. Use the search box to filter by a method name or an idea, and the copy buttons to paste snippets into your editor.
Sections
- Variables and types – const, let, typeof, nullish coalescing, optional chaining and logical assignment.
- Strings – template literals, searching, slicing, splitting, padding and replaceAll.
- Arrays – map, filter, reduce, find, some, every, flat, spread and non-mutating sorting.
- Objects – destructuring, spread, Object.entries, structuredClone and computed keys.
- Functions – arrow functions, default and rest parameters, call, apply and bind, generators.
- Async and promises – async/await, chaining, Promise.all, allSettled and race, fetch and timers.
- DOM – querySelector, classList, event listeners, dataset and localStorage.
- Classes and modules – inheritance, private fields, import and export, try and catch.
Habits that prevent bugs
Prefer const and let over var. Compare with = instead of . Use optional chaining instead of long chains of && checks. Remember that map and filter return new arrays but sort and reverse mutate the original unless you use toSorted and toReversed. Always handle promise rejections with try and catch around await or a catch handler, and set a timeout or an abort signal on network requests that might hang.
Where to run the examples
Open your browser DevTools console, use Node.js in a terminal, or paste snippets into a small file and run it. Everything on this sheet works in current versions of Chrome, Firefox, Safari, Edge and Node.js.
Frequently Asked Questions
What is the difference between let, const and var?
let and const are block scoped; const cannot be reassigned, though the object it points to can still change. var is function scoped, is hoisted and allows redeclaration, so modern code uses const by default and let when a value must change.
When should I use map, filter and reduce?
Use map to transform every item, filter to keep some items and reduce to combine items into a single value. All three return new values and leave the original array unchanged.
What is the difference between ?? and ||?
|| falls back for any falsy value (0, empty string, false), while ?? only falls back for null and undefined. Use ?? when 0 or an empty string are valid values.
What is the difference between Promise.all and Promise.allSettled?
Promise.all rejects as soon as one promise rejects. Promise.allSettled always waits for every promise and reports a status and value or reason for each one.