Cheatsheets / JavaScript

JavaScript Cheatsheet

Complete JavaScript reference. Hit Ctrl+P to print.

Variables & Types

const name = valueBlock-scoped, no reassignment (preferred)
let name = valueBlock-scoped, reassignable
var name = valueFunction-scoped, hoisted — avoid in modern code
typeof valueReturns type as string: "number", "string", "boolean", "object", "undefined", "function", "symbol", "bigint"
42 / 3.14 / NaN / InfinityNumber types
"text" / 'text' / `template`String types
true / falseBoolean
nullIntentional absence of a value
undefinedVariable declared but not assigned
Symbol("desc")Unique, immutable identifier
9007199254740991nBigInt literal (suffix n)
Number("42")Convert to number
String(42)Convert to string
Boolean(0)Convert to boolean (0, "", null, undefined, NaN, false are falsy)
parseInt("42px", 10)Parse integer with radix
parseFloat("3.14em")Parse floating-point number
Number.isNaN(value)Check for NaN (safer than global isNaN)
Number.isFinite(value)Check for finite number

Strings

`Hello, ${name}!`Template literal with expression interpolation
str.lengthNumber of characters
str[0] / str.at(-1).at() supports negative indexes
str.includes("sub")Returns true if substring found
str.startsWith("sub") / str.endsWith("sub")Check prefix/suffix
str.indexOf("sub")First index of substring (-1 if not found)
str.slice(start, end)Extract substring (negative indexes count from end)
str.split(",")Split into array on delimiter
str.trim() / trimStart() / trimEnd()Remove whitespace
str.toUpperCase() / toLowerCase()Change case
str.replace("a", "b")Replace first match
str.replaceAll("a", "b")Replace all matches
str.repeat(3)Repeat string N times
str.padStart(10, "0") / padEnd()Pad to target length
str.match(/regex/g)Returns array of all matches
"a,b,c".split(",").join(" - ")Split then re-join with new separator

Arrays

const arr = [1, 2, 3]Array literal
arr.lengthNumber of elements
arr.push(val)Add to end; returns new length
arr.pop()Remove and return last element
arr.unshift(val)Add to start; returns new length
arr.shift()Remove and return first element
arr.indexOf(val)First index of value (-1 if not found)
arr.includes(val)Returns true if value exists
arr.find(x => x > 3)First element matching condition
arr.findIndex(x => x > 3)Index of first match
arr.filter(x => x > 2)New array of matching elements
arr.map(x => x * 2)New array with each element transformed
arr.reduce((acc, x) => acc + x, 0)Reduce to single value; 0 is initial accumulator
arr.forEach(x => { ... })Iterate — returns undefined
arr.some(x => x > 3)True if any element matches
arr.every(x => x > 0)True if all elements match
arr.slice(1, 3)Shallow copy of portion (non-mutating)
arr.splice(1, 2, "a")Remove 2 at index 1, insert "a" (mutates)
arr.sort((a, b) => a - b)Sort ascending by number (mutates)
arr.reverse()Reverse in place (mutates)
[...arr]Spread — shallow copy
[...arr1, ...arr2]Merge arrays
arr.flat(Infinity)Flatten nested arrays
arr.flatMap(x => [x, x*2])Map then flatten one level
Array.from("abc")Create array from iterable
Array.isArray(val)Test if value is an array

Objects

const obj = { a: 1, b: 2 }Object literal
obj.a / obj["a"]Dot notation vs bracket notation
const { a, b } = objDestructure into variables
const { a: renamed } = objDestructure with rename
const { a = 10 } = objDestructure with default value
const { a, ...rest } = objDestructure and collect remainder
{ ...obj, c: 3 }Spread — shallow copy and override/add
Object.keys(obj)Array of own enumerable keys
Object.values(obj)Array of own enumerable values
Object.entries(obj)Array of [key, value] pairs
Object.fromEntries(entries)Create object from [key, value] pairs
Object.assign({}, obj, overrides)Shallow merge (mutates first arg)
Object.freeze(obj)Prevent property additions or changes
"key" in objCheck if key exists (includes prototype)
obj.hasOwnProperty("key")Check own property only
delete obj.keyRemove a property
const key = "name"; obj[key]Computed property access
{ [key]: value }Computed property name in literal

Functions

function name(a, b) { return a + b; }Function declaration (hoisted)
const name = function(a, b) { return a + b; }Function expression (not hoisted)
const name = (a, b) => a + bArrow function (implicit return)
const name = (a, b) => { return a + b; }Arrow function (block body)
function greet(name = "World") { }Default parameter
function sum(...nums) { }Rest parameter — collects remaining args as array
fn(...arr)Spread arguments from array
const { a, b } = optionsObject destructuring in parameters
function outer() { return function inner() {} }Closure — inner has access to outer scope
(function() { ... })()IIFE — Immediately Invoked Function Expression
fn.call(thisArg, a, b)Call with explicit this and arguments
fn.apply(thisArg, [a, b])Call with explicit this and args as array
const bound = fn.bind(thisArg)Return new function with fixed this
function* gen() { yield 1; yield 2; }Generator function
const memo = (fn) => { const cache = {}; ... }Memoisation pattern

DOM Manipulation

document.querySelector(".cls")First matching element (CSS selector)
document.querySelectorAll("li")All matching elements (NodeList)
document.getElementById("id")Element by ID
document.createElement("div")Create new element
parent.appendChild(child)Add child to end of parent
parent.prepend(child)Add child to start of parent
parent.insertBefore(new, ref)Insert before reference node
el.before(node) / el.after(node)Insert sibling before/after element
parent.removeChild(child)Remove child from parent
el.remove()Remove element from DOM
el.cloneNode(true)Deep clone element and its children
el.innerHTML = "<p>html</p>"Set inner HTML (XSS risk — sanitize untrusted input)
el.textContent = "text"Set text content (safe — no HTML parsing)
el.getAttribute("href")Get attribute value
el.setAttribute("href", "url")Set attribute
el.removeAttribute("href")Remove attribute
el.dataset.keyAccess data-key attribute
el.classList.add("active")Add CSS class
el.classList.remove("active")Remove CSS class
el.classList.toggle("active")Toggle CSS class
el.classList.contains("active")Check if class exists
el.style.color = "red"Set inline style property
window.getComputedStyle(el)Get resolved CSS values
el.getBoundingClientRect()Get element position and dimensions
el.scrollIntoView({ behavior: "smooth" })Scroll element into view

Events

el.addEventListener("click", handler)Attach event listener
el.removeEventListener("click", handler)Remove listener (same function reference needed)
el.addEventListener("click", handler, { once: true })Auto-remove after first trigger
event.preventDefault()Stop default behaviour (e.g. form submit, link navigation)
event.stopPropagation()Stop event bubbling up the DOM
event.targetElement that triggered the event
event.currentTargetElement the listener is attached to
new CustomEvent("myEvent", { detail: data })Create custom event with payload
el.dispatchEvent(event)Programmatically fire an event
// Event delegationAttach listener to parent, check event.target — avoids attaching many listeners
document.addEventListener("DOMContentLoaded", fn)Run after HTML parsed (before images)
window.addEventListener("load", fn)Run after everything loaded (including images)
window.addEventListener("resize", fn)Viewport resize
window.addEventListener("scroll", fn)Page scroll
input.addEventListener("input", fn)Fires on every keystroke
input.addEventListener("change", fn)Fires when value committed (blur or Enter)
form.addEventListener("submit", fn)Form submission
"keydown" / "keyup" / "keypress"Keyboard events (keypress deprecated)
"mousedown" / "mouseup" / "mousemove"Mouse button and movement events
"touchstart" / "touchend" / "touchmove"Touch events
"focus" / "blur" / "focusin" / "focusout"Focus events (focusin/out bubble, focus/blur do not)
"pointerdown" / "pointermove" / "pointerup"Unified pointer events (mouse + touch + pen)

Fetch & Async

fetch(url)Returns a Promise resolving to a Response
fetch(url).then(r => r.json()).then(data => { ... })Chain .then() calls
const res = await fetch(url)Await fetch (inside async function)
const data = await res.json()Parse JSON response body
const text = await res.text()Parse text response body
res.okTrue if status 200–299
res.statusHTTP status code
fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(data) })POST with JSON body
async function name() { return value; }Async function — always returns a Promise
try { await fn(); } catch (err) { }Error handling with async/await
Promise.all([p1, p2])Wait for all promises — fails fast on any rejection
Promise.allSettled([p1, p2])Wait for all — returns results regardless of rejection
Promise.race([p1, p2])Resolve/reject with the first settled promise
Promise.any([p1, p2])Resolve with first fulfilled (ignores rejections)
new Promise((resolve, reject) => { })Construct a Promise manually
const controller = new AbortController()Create abort controller
fetch(url, { signal: controller.signal })Attach abort signal to fetch
controller.abort()Cancel the fetch

ES6+ Syntax

`Hello, ${name}`Template literal
const [a, b, ...rest] = arrArray destructuring with rest
const { x = 0, y = 0 } = pointObject destructuring with defaults
const copy = { ...original, key: val }Object spread with override
const arr2 = [...arr1, 4, 5]Array spread
obj?.prop?.nestedOptional chaining — returns undefined if null/undefined
arr?.[0]Optional chaining on array index
fn?.()Optional chaining on function call
val ?? "default"Nullish coalescing — use default only if null or undefined
val ??= "default"Nullish assignment — assign only if null/undefined
a ||= bLogical OR assignment — assign b if a is falsy
a &&= bLogical AND assignment — assign b if a is truthy
import { fn } from "./module.js"Named import
import defaultExport from "./module.js"Default import
import * as mod from "./module.js"Namespace import
export const fn = () => { }Named export
export default fnDefault export
const mod = await import("./module.js")Dynamic import (lazy loading)
class Animal { constructor(name) { this.name = name; } }Class declaration
class Dog extends Animal { bark() { } }Class inheritance with extends
super(args) / super.method()Call parent constructor or method
get name() { } / set name(v) { }Getter and setter
static create() { }Static class method
#private = 0Private class field (ES2022)

Error Handling

try { } catch (err) { } finally { }try runs, catch handles errors, finally always runs
err.messageHuman-readable error description
err.nameError type name (e.g. "TypeError")
err.stackStack trace string
throw new Error("message")Throw a generic error
throw new TypeError("expected string")Throw specific error type
throw new RangeError("out of bounds")Value out of allowed range
throw new ReferenceError("not defined")Invalid reference
class AppError extends Error { constructor(msg, code) { super(msg); this.code = code; } }Custom error class
err instanceof TypeErrorCheck error type
console.error(err)Log error to console
window.addEventListener("error", handler)Global uncaught error handler
window.addEventListener("unhandledrejection", handler)Unhandled Promise rejection handler