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
| Syntax | What it does | Lesson |
|---|
const x = 1; | Can't be reassigned (default choice) | Variables |
let y = 2; | Can be reassigned | Variables |
typeof x | "string", "number", "boolean"… | Data types |
Array.isArray(a) | Is it an array? | Data types |
Number("5") String(5) | Convert types | Data types |
null / undefined | Empty on purpose / not set | Data types |
Operators
| Syntax | What it does | Lesson |
|---|
+ - * / % ** | Maths (% remainder, ** power) | Operators |
x += 5 x++ | Update shortcuts | Operators |
=== !== | Strict equal / not equal | Comparisons |
&& || ! | And, or, not | Operators |
a ?? b | b if a is null/undefined | Operators |
c ? x : y | Ternary: one-line if/else | Operators |
obj?.prop | Optional chaining (no error if missing) | Objects |
Numbers
| Syntax | What it does | Lesson |
|---|
Math.round() floor() ceil() | Rounding | Numbers |
Math.floor(Math.random() * n) | Random 0 to n-1 | Numbers |
Math.max(...arr) | Largest value | Numbers |
n.toFixed(2) | "3.14" (string) | Numbers |
parseInt("42px") | 42 | Numbers |
Number.isNaN(x) | Is it NaN? | Numbers |
Conditions & loops
| Syntax | What it does | Lesson |
|---|
if (c) { } else if (d) { } else { } | Branching | if…else |
switch (v) { case 1: … break; } | Match one value | switch |
for (let i = 0; i < n; i++) | Counting loop | for loops |
for (const item of list) | Loop over values | for loops |
for (const key in obj) | Loop over object keys | for loops |
while (c) { } | Repeat while true | while loops |
break / continue | Stop loop / skip to next | while loops |
Functions
| Syntax | What it does | Lesson |
|---|
function add(a, b) { return a + b; } | Function declaration | Functions |
const add = (a, b) => a + b; | Arrow function | Arrow functions |
function f(x = 10) { } | Default parameter | Functions |
function f(...nums) { } | Rest parameter | Destructuring & spread |
{ } block scope | let/const live inside braces | Scope |
Arrays
| Syntax | What it does | Lesson |
|---|
arr.push(x) / arr.pop() | Add / remove at end | Arrays |
arr.unshift(x) / arr.shift() | Add / remove at start | Arrays |
arr.includes(x) arr.indexOf(x) | Find a value | Arrays |
arr.map(x => x * 2) | Transform every item | Array methods |
arr.filter(x => x > 2) | Keep matching items | Array methods |
arr.find(x => x.id === 3) | First match | Array methods |
arr.reduce((sum, x) => sum + x, 0) | Combine into one value | Array methods |
arr.some() / arr.every() | Any / all match? | Array methods |
arr.toSorted((a, b) => a - b) | Sorted copy | Array methods |
DOM & events
| Syntax | What it does | Lesson |
|---|
document.querySelector(".x") | First match | DOM selecting |
document.querySelectorAll("li") | All matches | DOM selecting |
el.textContent = "Hi" | Change text | DOM manipulation |
el.classList.toggle("open") | Add/remove a class | DOM manipulation |
document.createElement("li") + append | Add elements | Create elements |
el.closest(".card") / el.remove() | Find an ancestor / remove | Create elements |
list.addEventListener("click", e => e.target.closest("li")) | Event delegation | Event delegation |
new FormData(form) | Read a whole form | Forms |
el.addEventListener("click", fn) | React to events | Events |
event.preventDefault() | Stop default action | Events |
setTimeout(fn, 1000) | Run once later | Timers |
Data & async
| Syntax | What it does | Lesson |
|---|
JSON.stringify(obj) / JSON.parse(str) | Object ↔ text | JSON |
localStorage.setItem("k", v) | Save in the browser | Local storage |
try { } catch (err) { } | Handle errors | Errors |
promise.then().catch() | Use a promise | Promises |
const data = await fetch(url) | Wait inside async functions | Async/await |
const res = await fetch(url); await res.json() | Load JSON from an API | Fetch API |
export / import { x } from "./x.js" | Modules | Modules |
Data tools
| Syntax | What it does | Lesson |
|---|
list.toSorted((a, b) => a - b) | Sort numbers (copy) | Sort & search |
users.find(u => u.id === 7) | First match | Sort & search |
[...new Set(list)] | Remove duplicates | Sets & Maps |
new Map([["a", 1]]) | Key-value pairs, any key | Sets & Maps |
structuredClone(obj) | Deep copy | Object methods |
/^d{4}$/.test(pin) | Validate with regex | Regex |
date.toLocaleDateString("en-GB") | Format a date | Dates |
Browser & performance
| Syntax | What it does | Lesson |
|---|
new URLSearchParams(location.search).get("q") | Read the URL | Browser APIs |
matchMedia("(min-width: 768px)").matches | Media query in JS | Responsive JS |
debounce(fn, 300) | Run after typing stops | Debounce & throttle |
requestAnimationFrame(loop) | Smooth animation | Canvas |
queueMicrotask(fn) | Run right after this task | Event loop |
new Worker("worker.js") | Background thread | Web Workers |
console.table(data) / debugger; | Debug | Debugging |
The JavaScript lessons behind this cheat sheet