JavaScript Cheat Sheet

Modern JavaScript syntax and methods at a glance.

​
Variables and typesStringsArraysObjectsFunctionsAsync and promisesDOMClasses and modules
55 entries

Variables and types

const x = 1

Block-scoped constant binding

let y = 2

Block-scoped variable

typeof value

Type name: "string", "number", "object", "undefined" ...

Number.isInteger(n)

Check for an integer

value ?? fallback

Nullish coalescing: fallback only for null / undefined

obj?.a?.b

Optional chaining: undefined instead of a TypeError

a ||= b, a &&= b, a ??= b

Logical assignment operators

Strings

`Hi ${name}`

Template literal with interpolation

s.includes("a") / startsWith / endsWith

Substring 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 } = obj

Destructuring 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 + b

Arrow function

function f(a, b = 2, ...rest) {}

Default and rest parameters

fn.call(ctx, a) / apply / bind

Control 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 / toggle

Change classes

el.addEventListener("click", fn)

Attach an event listener

el.dataset.id

Read 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 = 2

Static and private fields

import x, { y } from "./m.js"

ES module import

export default x; export const y = 1

ES 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

  1. Variables and types – const, let, typeof, nullish coalescing, optional chaining and logical assignment.
  2. Strings – template literals, searching, slicing, splitting, padding and replaceAll.
  3. Arrays – map, filter, reduce, find, some, every, flat, spread and non-mutating sorting.
  4. Objects – destructuring, spread, Object.entries, structuredClone and computed keys.
  5. Functions – arrow functions, default and rest parameters, call, apply and bind, generators.
  6. Async and promises – async/await, chaining, Promise.all, allSettled and race, fetch and timers.
  7. DOM – querySelector, classList, event listeners, dataset and localStorage.
  8. 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

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.

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.

|| 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.

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.