JavaScriptPrintable

JavaScript Cheat Sheet

Variables, operators, strings, arrays, objects, the DOM, events and async code. The JavaScript you reach for every day, on one page.

Variables & types

SyntaxWhat it doesLesson
const x = 1;Can't be reassigned (default choice)Variables
let y = 2;Can be reassignedVariables
typeof x"string", "number", "boolean"…Data types
Array.isArray(a)Is it an array?Data types
Number("5") String(5)Convert typesData types
null / undefinedEmpty on purpose / not setData types

Operators

SyntaxWhat it doesLesson
+ - * / % **Maths (% remainder, ** power)Operators
x += 5 x++Update shortcutsOperators
=== !==Strict equal / not equalComparisons
&& || !And, or, notOperators
a ?? bb if a is null/undefinedOperators
c ? x : yTernary: one-line if/elseOperators
obj?.propOptional chaining (no error if missing)Objects

Strings

SyntaxWhat it doesLesson
`Hi ${name}`Template literalStrings
s.length s[0] s.at(-1)Length, first, last characterStrings
s.toUpperCase() s.trim()Change case / remove spacesString methods
s.includes("x")Contains?String methods
s.slice(0, 3)Part of a stringString methods
s.split(",")String → arrayString methods
s.replaceAll("a", "b")Replace every matchString methods

Numbers

SyntaxWhat it doesLesson
Math.round() floor() ceil()RoundingNumbers
Math.floor(Math.random() * n)Random 0 to n-1Numbers
Math.max(...arr)Largest valueNumbers
n.toFixed(2)"3.14" (string)Numbers
parseInt("42px")42Numbers
Number.isNaN(x)Is it NaN?Numbers

Conditions & loops

SyntaxWhat it doesLesson
if (c) { } else if (d) { } else { }Branchingif…else
switch (v) { case 1: … break; }Match one valueswitch
for (let i = 0; i < n; i++)Counting loopfor loops
for (const item of list)Loop over valuesfor loops
for (const key in obj)Loop over object keysfor loops
while (c) { }Repeat while truewhile loops
break / continueStop loop / skip to nextwhile loops

Functions

SyntaxWhat it doesLesson
function add(a, b) { return a + b; }Function declarationFunctions
const add = (a, b) => a + b;Arrow functionArrow functions
function f(x = 10) { }Default parameterFunctions
function f(...nums) { }Rest parameterDestructuring & spread
{ } block scopelet/const live inside bracesScope

Arrays

SyntaxWhat it doesLesson
arr.push(x) / arr.pop()Add / remove at endArrays
arr.unshift(x) / arr.shift()Add / remove at startArrays
arr.includes(x) arr.indexOf(x)Find a valueArrays
arr.map(x => x * 2)Transform every itemArray methods
arr.filter(x => x > 2)Keep matching itemsArray methods
arr.find(x => x.id === 3)First matchArray methods
arr.reduce((sum, x) => sum + x, 0)Combine into one valueArray methods
arr.some() / arr.every()Any / all match?Array methods
arr.toSorted((a, b) => a - b)Sorted copyArray methods

Objects

SyntaxWhat it doesLesson
const o = { name: "Ada", age: 36 }Object literalObjects
o.name / o["name"]Read a propertyObjects
Object.keys(o) Object.entries(o)Keys / [key, value] pairsObjects
const { name } = oDestructuringDestructuring & spread
{ ...o, age: 37 }Copy with changesDestructuring & spread
class Dog { constructor() {} }Class blueprintClasses

DOM & events

SyntaxWhat it doesLesson
document.querySelector(".x")First matchDOM selecting
document.querySelectorAll("li")All matchesDOM selecting
el.textContent = "Hi"Change textDOM manipulation
el.classList.toggle("open")Add/remove a classDOM manipulation
document.createElement("li") + appendAdd elementsCreate elements
el.closest(".card") / el.remove()Find an ancestor / removeCreate elements
list.addEventListener("click", e => e.target.closest("li"))Event delegationEvent delegation
new FormData(form)Read a whole formForms
el.addEventListener("click", fn)React to eventsEvents
event.preventDefault()Stop default actionEvents
setTimeout(fn, 1000)Run once laterTimers

Data & async

SyntaxWhat it doesLesson
JSON.stringify(obj) / JSON.parse(str)Object ↔ textJSON
localStorage.setItem("k", v)Save in the browserLocal storage
try { } catch (err) { }Handle errorsErrors
promise.then().catch()Use a promisePromises
const data = await fetch(url)Wait inside async functionsAsync/await
const res = await fetch(url); await res.json()Load JSON from an APIFetch API
export / import { x } from "./x.js"ModulesModules

Logic & functions

SyntaxWhat it doesLesson
a && b / a || b / !aAnd, or, notLogical operators
value ?? "default"Default only for null or undefinedLogical operators
user?.address?.cityRead safelyLogical operators
for (const x of list) / break / continueLoop over values and control the loopfor...of & break
const add = (n) => (x) => x + nClosureCallbacks
fn.bind(obj)Fix thisthis & bind

Data tools

SyntaxWhat it doesLesson
list.toSorted((a, b) => a - b)Sort numbers (copy)Sort & search
users.find(u => u.id === 7)First matchSort & search
[...new Set(list)]Remove duplicatesSets & Maps
new Map([["a", 1]])Key-value pairs, any keySets & Maps
structuredClone(obj)Deep copyObject methods
/^d{4}$/.test(pin)Validate with regexRegex
date.toLocaleDateString("en-GB")Format a dateDates

Browser & performance

SyntaxWhat it doesLesson
new URLSearchParams(location.search).get("q")Read the URLBrowser APIs
matchMedia("(min-width: 768px)").matchesMedia query in JSResponsive JS
debounce(fn, 300)Run after typing stopsDebounce & throttle
requestAnimationFrame(loop)Smooth animationCanvas
queueMicrotask(fn)Run right after this taskEvent loop
new Worker("worker.js")Background threadWeb Workers
console.table(data) / debugger;DebugDebugging

The JavaScript lessons behind this cheat sheet