Variables & Types
const name = valueBlock-scoped, no reassignment (preferred)let name = valueBlock-scoped, reassignablevar name = valueFunction-scoped, hoisted — avoid in modern codetypeof valueReturns type as string: "number", "string", "boolean", "object", "undefined", "function", "symbol", "bigint"42 / 3.14 / NaN / InfinityNumber types"text" / 'text' / `template`String typestrue / falseBooleannullIntentional absence of a valueundefinedVariable declared but not assignedSymbol("desc")Unique, immutable identifier9007199254740991nBigInt literal (suffix n)Number("42")Convert to numberString(42)Convert to stringBoolean(0)Convert to boolean (0, "", null, undefined, NaN, false are falsy)parseInt("42px", 10)Parse integer with radixparseFloat("3.14em")Parse floating-point numberNumber.isNaN(value)Check for NaN (safer than global isNaN)Number.isFinite(value)Check for finite numberStrings
`Hello, ${name}!`Template literal with expression interpolationstr.lengthNumber of charactersstr[0] / str.at(-1).at() supports negative indexesstr.includes("sub")Returns true if substring foundstr.startsWith("sub") / str.endsWith("sub")Check prefix/suffixstr.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 delimiterstr.trim() / trimStart() / trimEnd()Remove whitespacestr.toUpperCase() / toLowerCase()Change casestr.replace("a", "b")Replace first matchstr.replaceAll("a", "b")Replace all matchesstr.repeat(3)Repeat string N timesstr.padStart(10, "0") / padEnd()Pad to target lengthstr.match(/regex/g)Returns array of all matches"a,b,c".split(",").join(" - ")Split then re-join with new separatorArrays
const arr = [1, 2, 3]Array literalarr.lengthNumber of elementsarr.push(val)Add to end; returns new lengtharr.pop()Remove and return last elementarr.unshift(val)Add to start; returns new lengtharr.shift()Remove and return first elementarr.indexOf(val)First index of value (-1 if not found)arr.includes(val)Returns true if value existsarr.find(x => x > 3)First element matching conditionarr.findIndex(x => x > 3)Index of first matcharr.filter(x => x > 2)New array of matching elementsarr.map(x => x * 2)New array with each element transformedarr.reduce((acc, x) => acc + x, 0)Reduce to single value; 0 is initial accumulatorarr.forEach(x => { ... })Iterate — returns undefinedarr.some(x => x > 3)True if any element matchesarr.every(x => x > 0)True if all elements matcharr.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 arraysarr.flat(Infinity)Flatten nested arraysarr.flatMap(x => [x, x*2])Map then flatten one levelArray.from("abc")Create array from iterableArray.isArray(val)Test if value is an arrayObjects
const obj = { a: 1, b: 2 }Object literalobj.a / obj["a"]Dot notation vs bracket notationconst { a, b } = objDestructure into variablesconst { a: renamed } = objDestructure with renameconst { a = 10 } = objDestructure with default valueconst { a, ...rest } = objDestructure and collect remainder{ ...obj, c: 3 }Spread — shallow copy and override/addObject.keys(obj)Array of own enumerable keysObject.values(obj)Array of own enumerable valuesObject.entries(obj)Array of [key, value] pairsObject.fromEntries(entries)Create object from [key, value] pairsObject.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 onlydelete obj.keyRemove a propertyconst key = "name"; obj[key]Computed property access{ [key]: value }Computed property name in literalFunctions
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 parameterfunction sum(...nums) { }Rest parameter — collects remaining args as arrayfn(...arr)Spread arguments from arrayconst { a, b } = optionsObject destructuring in parametersfunction outer() { return function inner() {} }Closure — inner has access to outer scope(function() { ... })()IIFE — Immediately Invoked Function Expressionfn.call(thisArg, a, b)Call with explicit this and argumentsfn.apply(thisArg, [a, b])Call with explicit this and args as arrayconst bound = fn.bind(thisArg)Return new function with fixed thisfunction* gen() { yield 1; yield 2; }Generator functionconst memo = (fn) => { const cache = {}; ... }Memoisation patternDOM Manipulation
document.querySelector(".cls")First matching element (CSS selector)document.querySelectorAll("li")All matching elements (NodeList)document.getElementById("id")Element by IDdocument.createElement("div")Create new elementparent.appendChild(child)Add child to end of parentparent.prepend(child)Add child to start of parentparent.insertBefore(new, ref)Insert before reference nodeel.before(node) / el.after(node)Insert sibling before/after elementparent.removeChild(child)Remove child from parentel.remove()Remove element from DOMel.cloneNode(true)Deep clone element and its childrenel.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 valueel.setAttribute("href", "url")Set attributeel.removeAttribute("href")Remove attributeel.dataset.keyAccess data-key attributeel.classList.add("active")Add CSS classel.classList.remove("active")Remove CSS classel.classList.toggle("active")Toggle CSS classel.classList.contains("active")Check if class existsel.style.color = "red"Set inline style propertywindow.getComputedStyle(el)Get resolved CSS valuesel.getBoundingClientRect()Get element position and dimensionsel.scrollIntoView({ behavior: "smooth" })Scroll element into viewEvents
el.addEventListener("click", handler)Attach event listenerel.removeEventListener("click", handler)Remove listener (same function reference needed)el.addEventListener("click", handler, { once: true })Auto-remove after first triggerevent.preventDefault()Stop default behaviour (e.g. form submit, link navigation)event.stopPropagation()Stop event bubbling up the DOMevent.targetElement that triggered the eventevent.currentTargetElement the listener is attached tonew CustomEvent("myEvent", { detail: data })Create custom event with payloadel.dispatchEvent(event)Programmatically fire an event// Event delegationAttach listener to parent, check event.target — avoids attaching many listenersdocument.addEventListener("DOMContentLoaded", fn)Run after HTML parsed (before images)window.addEventListener("load", fn)Run after everything loaded (including images)window.addEventListener("resize", fn)Viewport resizewindow.addEventListener("scroll", fn)Page scrollinput.addEventListener("input", fn)Fires on every keystrokeinput.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 Responsefetch(url).then(r => r.json()).then(data => { ... })Chain .then() callsconst res = await fetch(url)Await fetch (inside async function)const data = await res.json()Parse JSON response bodyconst text = await res.text()Parse text response bodyres.okTrue if status 200–299res.statusHTTP status codefetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(data) })POST with JSON bodyasync function name() { return value; }Async function — always returns a Promisetry { await fn(); } catch (err) { }Error handling with async/awaitPromise.all([p1, p2])Wait for all promises — fails fast on any rejectionPromise.allSettled([p1, p2])Wait for all — returns results regardless of rejectionPromise.race([p1, p2])Resolve/reject with the first settled promisePromise.any([p1, p2])Resolve with first fulfilled (ignores rejections)new Promise((resolve, reject) => { })Construct a Promise manuallyconst controller = new AbortController()Create abort controllerfetch(url, { signal: controller.signal })Attach abort signal to fetchcontroller.abort()Cancel the fetchES6+ Syntax
`Hello, ${name}`Template literalconst [a, b, ...rest] = arrArray destructuring with restconst { x = 0, y = 0 } = pointObject destructuring with defaultsconst copy = { ...original, key: val }Object spread with overrideconst arr2 = [...arr1, 4, 5]Array spreadobj?.prop?.nestedOptional chaining — returns undefined if null/undefinedarr?.[0]Optional chaining on array indexfn?.()Optional chaining on function callval ?? "default"Nullish coalescing — use default only if null or undefinedval ??= "default"Nullish assignment — assign only if null/undefineda ||= bLogical OR assignment — assign b if a is falsya &&= bLogical AND assignment — assign b if a is truthyimport { fn } from "./module.js"Named importimport defaultExport from "./module.js"Default importimport * as mod from "./module.js"Namespace importexport const fn = () => { }Named exportexport default fnDefault exportconst mod = await import("./module.js")Dynamic import (lazy loading)class Animal { constructor(name) { this.name = name; } }Class declarationclass Dog extends Animal { bark() { } }Class inheritance with extendssuper(args) / super.method()Call parent constructor or methodget name() { } / set name(v) { }Getter and setterstatic create() { }Static class method#private = 0Private class field (ES2022)Error Handling
try { } catch (err) { } finally { }try runs, catch handles errors, finally always runserr.messageHuman-readable error descriptionerr.nameError type name (e.g. "TypeError")err.stackStack trace stringthrow new Error("message")Throw a generic errorthrow new TypeError("expected string")Throw specific error typethrow new RangeError("out of bounds")Value out of allowed rangethrow new ReferenceError("not defined")Invalid referenceclass AppError extends Error { constructor(msg, code) { super(msg); this.code = code; } }Custom error classerr instanceof TypeErrorCheck error typeconsole.error(err)Log error to consolewindow.addEventListener("error", handler)Global uncaught error handlerwindow.addEventListener("unhandledrejection", handler)Unhandled Promise rejection handler