Skip to content

JavaScript Cheat Sheet — Complete Reference (75+ snippets, 2026)

Last verified May 2026 — runs in your browser
JavaScript Cheatsheet
const x = 10

Block-scoped constant

Variables
let y = 20

Block-scoped variable

Variables
typeof x

Get type as string

Variables
const { a, b } = obj

Object destructuring

Variables
const [a, b] = arr

Array destructuring

Variables
const merged = { ...obj1, ...obj2 }

Spread/merge objects

Variables
const copy = [...arr]

Spread/copy array

Variables
x ?? fallback

Nullish coalescing (null/undefined only)

Variables
obj?.prop?.nested

Optional chaining

Variables
[1, 2, 3]

Create an array

Arrays
arr.push(item)

Add item to end

Arrays
arr.pop()

Remove and return last item

Arrays
arr.shift() / arr.unshift(item)

Remove first / add to start

Arrays
arr.map(x => x * 2)

Transform each element

Arrays
arr.filter(x => x > 0)

Filter elements by condition

Arrays
arr.reduce((acc, x) => acc + x, 0)

Reduce to single value

Arrays
arr.find(x => x.id === 1)

Find first matching element

Arrays
arr.findIndex(x => x > 5)

Find index of first match

Arrays
arr.some(x => x > 0)

Check if any element matches

Arrays
arr.every(x => x > 0)

Check if all elements match

Arrays
arr.includes(item)

Check if item exists

Arrays
arr.flat(Infinity)

Flatten nested arrays

Arrays
arr.sort((a, b) => a - b)

Sort numerically ascending

Arrays
arr.slice(1, 3)

Get subarray (non-mutating)

Arrays
arr.splice(1, 2, ...items)

Remove/insert at index (mutating)

Arrays
[...new Set(arr)]

Remove duplicates

Arrays
Array.from({ length: 5 }, (_, i) => i)

Create array from range

Arrays
const obj = { key: "value" }

Create an object

Objects
Object.keys(obj)

Get array of keys

Objects
Object.values(obj)

Get array of values

Objects
Object.entries(obj)

Get array of [key, value] pairs

Objects
Object.assign({}, obj1, obj2)

Merge objects (shallow)

Objects
structuredClone(obj)

Deep clone an object

Objects
Object.freeze(obj)

Make object immutable (shallow)

Objects
"key" in obj

Check if key exists

Objects
delete obj.key

Delete a property

Objects
const { unwanted, ...rest } = obj

Omit a key via destructuring

Objects
function fn(x) { return x }

Function declaration

Functions
const fn = (x) => x * 2

Arrow function

Functions
const fn = (x = 10) => x

Default parameter

Functions
const fn = (...args) => args

Rest parameters

Functions
fn(1, ...arr)

Spread arguments

Functions
setTimeout(fn, 1000)

Delay execution by ms

Functions
setInterval(fn, 1000)

Repeat execution every ms

Functions
function* gen() { yield 1 }

Generator function

Functions
async function fn() { const res = await fetch(url); return res.json(); }

Async/await function

Promises
fetch(url).then(r => r.json())

Fetch with .then() chain

Promises
Promise.all([p1, p2])

Wait for all promises

Promises
Promise.race([p1, p2])

First promise to resolve/reject

Promises
Promise.allSettled([p1, p2])

Wait for all (resolved or rejected)

Promises
new Promise((resolve, reject) => { ... })

Create a new promise

Promises
try { await fn(); } catch (e) { console.error(e); }

Async error handling

Promises
`Hello ${name}`

Template literal

Strings
s.includes("sub")

Check if substring exists

Strings
s.startsWith("pre") / s.endsWith("suf")

Check start/end

Strings
s.split(",")

Split into array

Strings
s.trim()

Remove whitespace from both ends

Strings
s.replace(/regex/g, "new")

Replace with regex (global)

Strings
s.padStart(5, "0")

Pad start to length

Strings
s.repeat(3)

Repeat string N times

Strings
s.match(/pattern/g)

Find all regex matches

Strings
s.at(-1)

Get last character

Strings
document.querySelector(".class")

Select first matching element

DOM
document.querySelectorAll("div")

Select all matching elements

DOM
el.addEventListener("click", fn)

Add event listener

DOM
el.classList.add("active")

Add CSS class

DOM
el.classList.toggle("hidden")

Toggle CSS class

DOM
el.textContent = "text"

Set text content (safe)

DOM
el.setAttribute("data-id", "5")

Set HTML attribute

DOM
el.style.color = "red"

Set inline style

DOM
el.remove()

Remove element from DOM

DOM
const m = new Map()

Create a Map (any key type)

ES6+
const s = new Set([1, 2, 3])

Create a Set (unique values)

ES6+
for (const [k, v] of map) {}

Iterate over Map entries

ES6+
for (const item of iterable) {}

for...of loop

ES6+
Symbol("desc")

Create unique symbol

ES6+
import { fn } from "./module.js"

ES module import

ES6+
export default fn

Default export

ES6+
const proxy = new Proxy(target, handler)

Create a Proxy

ES6+
Showing 79 of 79 snippets

JavaScript Cheat Sheet — JS Reference & Syntax Guide

JavaScript landed in Netscape Navigator in 1995, written in ten days as a scripting layer for the browser, and has since accreted modules, classes, arrow functions, async/await and optional chaining — but the original equality rules, the original `this` binding and the original number type are still right there underneath. The reference below covers 75+ snippets across variables, arrays, objects, functions, promises, strings, DOM and ES6+. Most trouble in real code doesn't come from forgetting syntax. It comes from quirks that look ordinary but bite. `==` does type coercion and quietly returns true for `0 == ""`, which is why `===` is the default in lint configs. The keyword `this` inside a regular function callback refers to the global object or `undefined` in strict mode, not the surrounding instance — arrow functions exist mostly to fix that. `0.1 + 0.2` returns `0.30000000000000004` because floating point is binary, not decimal. These are the snippets reached for when debugging exactly that — the strict comparison, the arrow callback, the destructure that strips a key — without rereading the ECMAScript spec each time.

Common pitfalls in JavaScript

A few patterns earn their place on the first screen of any JavaScript file. `const` and `let` replace `var` because they respect block scope and don't hoist as `undefined` — a habit that prevents whole classes of bug from ever happening. Optional chaining `obj?.prop?.nested` short-circuits on `null` or `undefined` instead of throwing, and pairs naturally with the nullish coalescing operator `??` which only falls back on `null`/`undefined` (not `0` or `""`). `structuredClone(obj)` deep-clones an object without the JSON round-trip that loses dates, regexes and Maps. And `Array.from({ length: n }, (_, i) => i)` is the cleanest way to build a numeric range without a `for` loop. Async errors deserve a `try/catch` around `await` rather than a dangling `.catch()` — the stack traces are dramatically more useful. The cheatsheet groups all of this into variables, arrays, objects, functions, promises, strings, DOM and ES6+ so the right section is one click away.

  • 75+ practical JavaScript snippets
  • 9 categories including DOM and ES6+
  • Search across code and descriptions
  • Filter by category
  • One-click copy to clipboard
  • Covers modern ES2023+ features

Free. No signup. Your inputs stay in your browser. Ads via Google AdSense (consent required).