Skip to main content

JavaScript Real World Vademecum

JavaScript Complete Cheat Sheet

A comprehensive quick reference guide containing all the syntax, methods, and patterns covered in the previous chapters.


CategoryTool/ConceptAnalogy/PurposeExample/Syntax
FOUNDATIONS - VARIABLES
letThe Whiteboard: mutable valuelet counter = 0;
counter = 1;
constThe Safe: immutable referenceconst USER_ID = 123;
const user = {name: 'Mario'}; user.name = 'Luigi'; (OK)
varThe Old Way (avoid!)Has function scope and problematic hoisting
null vs undefinedIntentional empty vs. Accidental emptylet x = null; (chosen by you)
let y; (value of y is undefined)
FOUNDATIONS - DATA TYPES
StringText with methodsconst s = "Hello";
Template Literals (` )Strings with "holes" for variables Hello ${name}``Total: ${price * 1.22}` ``
Escape charsSpecial characters\n (newline)
\t (tab)
" (quote)
\ (backslash)
.split()String Slicer"a-b-c".split('-')['a', 'b', 'c']
"hi".split('')['h', 'i']
.charCodeAt()Character → Number (Old)"A".charCodeAt(0)65 (breaks with emoji "🎉")
.codePointAt()Character → Number (Modern)"🎉".codePointAt(0)127881 (correct)
String.fromCharCode()Number → Character (Old)String.fromCharCode(65)"A" (doesn't handle emoji)
String.fromCodePoint()Number → Character (Modern)String.fromCodePoint(127881)"🎉"
.startsWith()Start Check (Intent)file.startsWith("doc")true
"Hello".startsWith("H")true
NumberIEEE 754, integers and decimalsconst n = 3.14;
Special ValuesNon-numbers and infinitiesInfinity, -Infinity
NaN (not equal to itself)
isNaN()Confused Customs Officer: "Is it... NaN?"isNaN("hi")true (converts first)
isNaN(null)false (because Number(null) is 0)
Number.isNaN()Strict Customs Officer: "Is it already NaN?"Number.isNaN("hi")false
Number.isNaN(NaN)true
Number()"All or nothing" conversion (strict)Number("42px")NaN
Number("123")123
parseInt()Integer Extractor (tolerant)parseInt("42.5px", 10)42
parseInt("1010", 2)10 (binary)
parseFloat()Decimal Extractor (tolerant)parseFloat("42.5px")42.5
parseFloat("3.14.15")3.14
MathBuilt-in scientific calculatorStatic object, e.g., Math.PI
Math.floor()Rounds down to floorMath.floor(4.9)4
Math.ceil()Rounds up to ceilingMath.ceil(4.1)5
Math.ceil(0.1)1
Math.round()Rounds to nearestMath.round(4.5)5
Math.round(4.4)4
Math.random()Randomness Generator (0 - 0.99...)Math.random()
Math.floor(Math.random() * 10) + 1 (from 1 to 10)
Math.pow() vs **ExponentiationMath.pow(2, 3)8
2 ** 38 (modern)
Math.sqrt()Square root (Readability)Math.sqrt(9)3 (better than 9 ** 0.5)
Problem (IEEE-754)"Wrong" decimal calculations0.1 + 0.20.30000000000000004
.toFixed()Solution to display (string!)(0.1 + 0.2).toFixed(2)"0.30"
parseFloat() (with toFixed)Solution to calculate (number)parseFloat((0.1 + 0.2).toFixed(2))0.30
new Date()Creates a date objectnew Date() (now)
new Date("2025-01-15")
Tricky Methods (Date)Watch out for bugs!getMonth()0-11 (January is 0!)
getDay()0-6 (Sunday is 0!)
Date.now()Timestamp (milliseconds)Date.now() (to measure performance or unique IDs)
BooleanTrue or Falsetrue / false
Truthy/FalsyThe "gray area" of truth6 falsy: false, 0, "", null, undefined, NaN
Everything else is truthy (even [] and {})
Creation [] vs Array()Empty egg cartonArray(5)[ <5 empty items> ] (not [5])
.lengthHow many items (property)arr[arr.length - 1] (last item)
arr.length = 0 (empties array)
Set and .sizeCollection of unique itemsnew Set([1,1,2]).size2
[...new Set([1,1,2])][1, 2]
.push() / .pop()Modifies the end (Destructive)arr.push(3) (adds)
arr.pop() (removes)
.unshift() / .shift()Modifies the start (Destructive)arr.unshift(1) (adds)
arr.shift() (removes)
.splice()Swiss Army Knife (Destructive)arr.splice(1, 2, 'X') (from index 1, remove 2, add 'X')
.sort()Sorts (Destructive!)arr.sort() (alphabetical!)
arr.sort((a, b) => a - b) (numeric)
.filter()Sieve/Filter (Creates new array)arr.filter(n => n > 2)
arr.filter(u => u.active)
.find()Detective (Finds the first)arr.find(n => n > 2)3 (or undefined)
.findIndex()Detective (Finds the index)arr.findIndex(n => n > 2)2 (or -1)
.includes()Checker (Is it there?)arr.includes(3)true
.indexOf()Locator (Where is it?)arr.indexOf(3)2 (or -1)
.join()Gluer (Array → String)['a','b'].join('-')"a-b"
['h','e','y'].join('')"hey"
.slice()Photocopier (Creates new array)arr.slice() (copy)
arr.slice(1, 3) (from index 1 to 3 excluded)
.map()Transformation Factoryarr.map(n => n * 2)
arr.map(u => u.name)
.reduce()Boiler/Reducer (Array → Single Value)arr.reduce((acc, n) => acc + n, 0) (sum)
arr.reduce((obj, k) => ({...obj, [k]: true}), {})
.some()At least one? (true/false)arr.some(n => n > 2)true
.every()Everyone? (true/false)arr.every(n => n > 0)true
.fill()Bridge for .map() on Array(N)Array(3).fill(0)[0, 0, 0]
Array(3).fill().map((*, i) => i)[0, 1, 2]
Pattern: Create RangeCombines Array(N), .fill, .mapArray(5).fill().map((*, i) => i + 1)[1, 2, 3, 4, 5]
Logic: MedianFind the center (requires sort)Handle length % 2 === 0 (even) vs else (odd)
Object Creation &#123;&#125;Container key: valueconst user = &#123; name: "Mario" &#125;
Nested ObjectsObjects inside objects (Organization)user.address = &#123; city: "Rome" &#125;
user.keys = &#123; right: false &#125;
Access . vs [] vs ?.Dot (static) vs Brackets (dynamic) vs Safeobj.name vs obj[myVar]
obj.job?.salary (safe)
Shorthand PropertiesES6 Shortcutconst user = &#123; name, age &#125; (if name and age exist)
Destructuring"Unpacking" objectsconst &#123; name, age &#125; = user;
const &#123; name: userName &#125; = user;
Object.keys()Array of keys onlyObject.keys(user)['name', 'age']
Object.values()Array of values onlyObject.values(user)['Mario', 30]
Object.entries()Array of [k, v] pairsObject.entries(user).forEach(([key, val]) => ...)
hasOwnProperty()Property check (Old)user.hasOwnProperty('name')true
Object.hasOwn()Property check (Modern)Object.hasOwn(user, 'name')true
Pattern: Frequency MapCount occurrences`counts[item] = (counts[item]
FOUNDATIONS - OPERATORS
`` (OR)
! (NOT) and "Toggle"Boolean InverterisMenuOpen = !isMenuOpen;
if (!user) &#123; ... &#125;
... (Spread)"Empty the box" (Array/Objects)const copy = [...arr];
const o2 = &#123;...o1, b: 2&#125;;
** (Exponentiation)Power calculation (Modern)2 ** 38
9 ** 0.53
Chained AssignmentMultiple initialization (risky)a = b = c = 10; (Avoid if possible)
CONTROL - OUTPUT AND COMMENTS
consoleCockpit (Debug)console.log(variable)
console.error("Error!")
console.table()Visualize arrays/objectsconsole.table(arrayOfObjects)
Comments // /* */Notes (Why, not What)// Failed attempts counter
JSDoc /** */Formal documentation/** @param &#123;string&#125; name ... */
Tags TODO FIXME NOTEWork organization// FIXME: Doesn't handle negative numbers
CONTROL - FLOW
if/else if/elseDecision Forkif (x > 10) &#123; ... &#125; else &#123; ... &#125;
Ternary OperatorCompact if/else (for assignment)const status = age >= 18 ? "Adult" : "Minor"
el.style.display = isVisible ? "block" : "none"
switchSwitchboard (for static values)switch (action) &#123; case 'save': ... break; default: ... &#125;
Return Early (Guard Clauses)Bouncer (Validate and exit immediately)function f(user) &#123; if (!user) return; ... &#125;
CONTROL - LOOPS
forIndustrial Robot (knows # of laps)for (let i = 0; i < 10; i++) &#123; ... &#125;
whileNight Watchman (condition)while (x < 10) &#123; x++; &#125;
do...whileAct first, ask later (at least 1 lap)do &#123; ... &#125; while (cond); (for menus)
for...ofElegant Explorer (for values)for (const el of array) &#123; ... &#125;
for (const char of "hello") &#123; ... &#125;
forEachForeman (only for Arrays)arr.forEach((el, i) => console.log(i, el))
breakEmergency Stop (Exit the loop)if (x === 5) break;
continueSkip to next lapif (x % 2 === 0) continue;
FUNCTIONS AND SCOPE
Declaration vs Arrow =>function (has this) vs => (inherits this)function f() &#123;&#125; vs const f = () => &#123;&#125;
Implicit Return (Arrow)One-liner (without &#123;&#125;)n => n * 2
Return Object (Arrow)Requires () around &#123;&#125;() => (&#123; name: "Mario" &#125;) (NOT () => &#123; name: "Mario" &#125;)
Default ParametersFallback valuesfunction f(n = 10) &#123; ... &#125;
Destructuring (Params)"Unpack" argumentsfunction f(&#123; id, name &#125;) &#123; ... &#125;
function g([first, second]) &#123; ... &#125;
CallbackRecipe passed as argumentarr.map(n => n * 2) (n => n*2 is the callback)
btn.addEventListener('click', () => ...)
CurryingFunction factoryconst add = a => b => a + b;
const add10 = add(10); add10(5);15
Underscore Convention _Ignored parameterarr.map((_el, index) => index)
btn.addEventListener('click', _ => console.log('click'))
Global ScopePublic Square (visible to all)Variable outside everything
Local/Function ScopePrivate Living Room (visible only in function)function f() &#123; let x = 5; &#125;
Block ScopeCloset/Storage (visible only in &#123;&#125;)let and const in if, for, while
Scope ChainKey Search (Pocket → Room → House)Searches from inside to outside
CLASSES (OOP)
classCookie Cutter (Blueprint)class Player &#123; ... &#125;
Syntactic SugarModern Mask for prototypetypeof Player"function"
constructor()Assembly Department (called by new)constructor(x, y) &#123; this.x = x; &#125;
new"Create" Command (The 4 steps)const p = new Player(10, 20)
thisContext ("this specific cookie")this.lives = 3;
Class PropertiesFactory settingsclass P &#123; lives = 3; &#125; (outside constructor)
Methods (in prototype)Shared Backpack (Abilities)jump() &#123; this.y -= 10; &#125;
Pattern: claim()Method to "deactivate" an instancethis.width = 0; this.y = Infinity; this.claimed = true;
DOM - LOADING
<script> Placementhead vs body<script> before </body> (old but safe)
defer (Best Practice)Download in parallel, execute after<script src="..." defer></script> (in head)
window.onloadWaits for everything (images included)Slow, avoid if not needed
DOMContentLoadedWaits only for HTML/DOM (Fast)window.addEventListener('DOMContentLoaded', () => ...)
DOM - MANIPULATION
querySelector / AllModern GPS (Uses CSS selectors)document.querySelector(".btn-primary")
document.querySelectorAll("ul > li")
getElementByIdFast for IDsdocument.getElementById("main-header")
getElementsByClassNameOld Way (Returns live HTMLCollection)document.getElementsByClassName("note")
Converting NodeList/Coll.Transforms into real Array[...nodelist]
Array.from(nodelist)
Properties vs MethodsNouns (data) vs Verbs (actions)el.id = "..." (Prop) vs el.remove() (Method)
HTML Attributes vs DOM PropsBlueprint vs Real Houseinput.value (reality) vs input.getAttribute('value') (blueprint)
document.createElement()Factory (Creates in memory)const p = document.createElement("p")
container.appendChild()Installation (Add to page)container.appendChild(p)
textContent (Safe)Marker (Only text, no HTML)el.textContent = "Hi <strong>"Hi <strong>
innerHTML (Dangerous)Magic Pen (Interprets HTML)el.innerHTML = "<strong>Hi</strong>"Hi (XSS Risk)
style.propertyInline style (dirty)el.style.backgroundColor = "red" (use camelCase)
classList (Best Practice)Label (JS state, CSS look)el.classList.add('is-hidden')
el.classList.toggle('active')
disabledBoolean Attribute (On/Off)btn.disabled = true; (unclickable)
btn.disabled = false; (re-enable)
disabled vs readonlyBarred Door vs Locked Glassreadonly is visible and sent with the form
Child Combinator >"Direct Child" Selectordiv > p (only children, not grandchildren)
DOM - EVENTS
onclick vs addEventListenerSingle Line vs SwitchboardaddEventListener (modern, multiple listeners)
Reference (fn) vs Execution (fn())Manual vs Cake (Pass the manual!)el.addEventListener('click', myFunction)
el.addEventListener('click', myFunction())
event ObjectDetailed Reporte.target (who triggered it)
e.key (key pressed)
e.preventDefault()Emergency Brake (Stop default action)form.addEventListener('submit', e => e.preventDefault()) (stop refresh)
Event DelegationBouncer (1 listener on parent)ul.addEventListener('click', e => &#123; if(e.target.tagName === 'LI') ... &#125;)
Problem: this and listenersthis becomes the button, not classbtn.addEventListener('click', this.method)
Solution: .bind(this)Glue this with supergluebtn.addEventListener('click', this.method.bind(this))
Solution: Arrow FunctionInherits this (Modern)btn.addEventListener('click', () => this.method())
keydown vs keyupKey Down vs Key Up (Use these)e.key === "ArrowUp"
keypress (Deprecated)Character typed (Ignores arrows, etc)Do not use
change vs input"Finished" (blur) vs "Real Time" (every key)input for reactive UX (e.g., live search)
change for final validation
submit<form> eventUse e.preventDefault()
confirm()Blocking dialog (Old)const yes = confirm("Sure?") (Avoid if possible)
DOM - DIALOG AND MODALS
<dialog>Portable Stage (Native HTML)<dialog id="modal">...</dialog>
showModal()Spotlight (Blocks page, backdrop, Esc)dialog.showModal() (What you want 99%)
show()Info Panel (Non-modal)dialog.show() (Page still active)
close()Exit Stagedialog.close("value")
dialog.addEventListener('close', () => ...)
API CANVAS AND GAMES
getContext("2d")Open the pencil case (Pens, markers)const ctx = canvas.getContext("2d")
Coordinates (0,0)Top LeftY increases going down (ctx.fillRect(0, 10, ...) is 10px from top)
fill vs strokeMarker (solid) vs Pen (outline)ctx.fillStyle = "red"
ctx.strokeStyle = "blue"
Shapes (Rectangles, Paths)Shortcuts (fillRect) vs Recipe (beginPath)ctx.fillRect(10, 10, 50, 50)
ctx.beginPath(); ctx.arc(...); ctx.fill();
Resolution vs SizePixels (JS) vs Dimensions (CSS)canvas.width = 1920 vs canvas.style.width = "100%"
Problem: Blurry Effect300x150 resolution "stretched"If JS width doesn't match CSS width
Solution: SynchronizationSet JS width equal to innerWidthcanvas.width = window.innerWidth (clears canvas!)
requestAnimationFrameGame Engine (60 FPS Loop)function loop() &#123; ...; requestAnimationFrame(loop); &#125;
Advantages vs setIntervalSynced, Auto-pause, FluidrAF is the king of animations (saves battery in background)
Logic: GravityAccel. modifies Velocity, Velocity modifies PositionvelY += grav; posY += velY;
Logic: Flag DebouncingTurnstile (Avoid 60 triggers/sec)if (coll && !isHit) &#123; isHit = true; ... &#125;
Logic: ResponsiveAuto-zoom (Adapts to viewport)player.width = proportionalSize(100)
PATTERNS AND BEST PRACTICES
Accumulator PatternFilling the bucket (loop)let total = 0; arr.forEach(n => total += n)
let html = ""; arr.forEach(s => html +=
  • ${s}
  • )
    Boolean FlagsState Switches (On/Off)let isLoading = true;``let hasError = false;
    State VariablesTraffic Light (Multiple states)let formState = "submitting" (vs "editing", "error")
    Configuration ObjectsControl Panel (No "magic numbers")const CONFIG = &#123; MAX_RETRIES: 3 &#125;
    try-catchSafety Net (Error handling)try &#123; JSON.parse(str) &#125; catch (e) &#123; ... &#125;``async function f() &#123; try &#123; await fetch(...) &#125; catch(e) &#123; ... &#125; &#125;
    Naming ConventionSpeaking Names (Readable code)isVisible (bool)fetchUsers (func)users (array)
    Incremental TestingTasting the sauce (Debug with console.log)Write-test-write-test
    Separation of ConcernsOne function = one task (SoC)Logic (JS) vs Presentation (CSS)
    style.display vs classListHand painting (dirty) vs Labeling (clean)Use classList (JS state, CSS look)el.classList.toggle("is-hidden")
    innerHTML = vs +=Replace (OK) vs Recreate (SLOW!)+= destroys and recreates entire DOM (use appendChild!)
    .className vs .classListWhole string vs Surgical KitUse classList (.add, .remove)
    .textContent vs innerHTMLMarker (Safe) vs Magic Pen (Dangerous)Use textContent for user data (prevents XSS)
    ImmutabilityMaking photocopies, not modifying originalsconst copy = [...arr, 4] (Avoid "Side Effects")
    .sort() vs .toSorted()Destructive (mutates) vs Immutable (copies).toSorted() (modern, doesn't modify original).slice().sort() (classic)
    Style: Readability vs ConciseTelling a story vs Being cleverReadability > Concise (for debug)const doubles = arr.map(n => n * 2) (concise ok)
    Swap AlgorithmCarousel (temp) vs Magic (Destructuring)[a, b] = [b, a] (modern)let temp = a; a = b; b = temp; (classic)
    Code EvolutionFrom Hardcoded to DRY to Event-DrivenDRY = Don't Repeat Yourself (use functions)
    STORAGE (localStorage)
    localStorageDrawer (Long-term memory)localStorage.setItem('key', 'value')``localStorage.getItem('key')
    Problem: The String WallThe Fax (Saves only strings)localStorage.setItem('user', &#123;name: 'a'&#125;)"[object Object]"
    JSON.stringify()Disassembler (Object → String)localStorage.setItem('user', JSON.stringify(user))
    JSON.parse()Reassembler (String → Object)const user = JSON.parse(localStorage.getItem('user'))
    Handling First RunFallback (Plan B)`const data = JSON.parse(localStorage.getItem('k'))
    Inspecting (DevTools)X-Ray Vision (Application Tab)Debug, edit, delete
    Limits5MB, Synchronous (slow), Insecure (sticky note)Do not save passwords!
    Advanced PatternsVersioning, Expiry, Namespaceconst k = "myApp_user" (namespace)setWithExpiry(key, val, ttl)
    CommandmentsThe 10 rules of localStorage"Thou shall save only strings", "Thou shall never trust", ...
    ALGORITHMS - REGEX
    /pattern/flagsText Metal Detector/hi/gi (global, case-insensitive)
    . ^ $ ``Wildcard, Start, End, OR
    [] (Character Class)Club (One of these)[aeiou] (vowels)
    [a-z0-9] (range)
    \d \w \s \bShortcuts (Digit, Word, Space, Boundary)/\bcat\b/ (whole word "cat")
    ? + * &#123;n,m&#125;Quantifiers (How many?)\d+ (one or more digits)
    colou?r (optional)
    `` (Escape)Special Power Deactivator. (literal dot)
    \ (literal backslash)
    () vs (?:...)Bus (Group) vs Photo (Capture)`(?:http
    Lookahead (?=...)"Followed by..." (doesn't consume)\d+(?=€) (number before €)
    \d+(?![a-z]) (number not followed by letter)
    Lookbehind (?<=...)"Preceded by..." (doesn't consume)(?<=€)\d+ (number after €)
    Real PatternsEmail, URL, PasswordemailRegex.test(email)
    ALGORITHMS - RECURSION
    Call Stack (LIFO)Stack of plates (Last In, First Out)Manages function execution order
    Stack OverflowToo many plates, stack collapsesInfinite recursion
    RecursionMatryoshka dolls (Function calls itself)return n * factorial(n - 1)
    Base CaseSolid doll (Stop condition)if (n <= 1) return 1;
    MemoizationSticky note (Cache for results)Avoids recalculations (e.g., Fibonacci)
    if (cache[n]) return cache[n];
    ALGORITHMS - TIMING
    setTimeout(fn, ms)Alarm Clock (Execute after ms)const t = setTimeout(() => ..., 1000)
    setInterval(fn, ms)Metronome (Execute every ms)const i = setInterval(() => ..., 1000)
    clearTimeout/IntervalCancel timerclearTimeout(t)
    clearInterval(i)
    setTimeout vs setIntervalDumb Clock (can overlap)Recursive setTimeout is safer for animations
    Debounce"Execute after user has finished"onkeyup in a search bar
    Throttle"Execute at most every X ms"onscroll to prevent overload
    ALGORITHMS - PRACTICAL
    Decimal → BinaryDivide by 2, read remaindersbinary = (num % 2) + binary; num = Math.floor(num / 2);
    Bubble SortBubbles (Simple but slow)if (arr[j] > arr[j+1]) [arr[j], arr[j+1]] = [arr[j+1], arr[j]]
    Quick SortDivide and Conquer (Fast)Choose pivot, divide into left/right, recursion
    Binary SearchDictionary Search (Requires sort)Cut search in half each loop (mid = floor((l+r)/2))
    Palindromestr === str.reverse()const c = str.toLowerCase().replace(...)
    return c === c.split('').reverse().join('')
    AnagramsSame lettersconst c1 = str1.split('').sort().join('')
    return c1 === c2;
    Prime Numbers (Test)Check divisors up to sqrt(n)for (let i = 2; i * i <= n; i++) ...
    Fibonacci (Iterative)Sum of previous two[prev, curr] = [curr, prev + curr]
    GCD (Euclidean)Greatest Common Divisorgcd(a, b) = gcd(b, a % b)
    PATTERNS - VALIDATION AND STATE
    Guard ClausesBouncer (Return early)if (!data) return;
    if (num < 0) return; (cleans code)
    SanitizationCleaning (Remove/Escape)str.replace(/[^a-z0-9]/g, '')
    el.textContent = str (sanitizes for HTML)
    ValidationCheck (Accept/Reject)emailRegex.test(email)
    Single Source of Truth (SSOT)Master Ledger (Single central state)Prevents out-of-sync data (e.g., const state = &#123; ... &#125;)
    CRUDCreate, Read, Update, DeletePattern to manage lists (e.g., TaskManager)
    Reset PatternState Factorystate = createInitialState() (avoids manual reset)