JSJavaScript · Lesson 14 of 14
JavaScript Cheatsheet
Modern JS on one page — ES6+ syntax, arrays, async, DOM.
JavaScript
// ── Basics ──────────────────────────────
const x = 42; // can't reassign (default)
let y = "hi"; // can reassign
`template ${x} literal` // interpolation
x === y // always use ===, never ==
typeof x // "number"
// ── Functions ───────────────────────────
function add(a, b = 0) { return a + b; }
const add2 = (a, b) => a + b; // arrow
const sq = n => n * n; // single param
// ── Destructuring & spread ──────────────
const { name, age = 18 } = person;
const [first, ...rest] = items;
const merged = { ...defaults, ...options };
const copy = [...arr];
// ── Control flow ────────────────────────
if (x > 10) {} else if (x > 5) {} else {}
for (const item of items) {} // values
for (const key in obj) {} // keys
items.forEach((item, i) => {});
const label = x > 10 ? "big" : "small";
value ?? fallback // null/undefined only
obj?.deep?.maybe // optional chainingJavaScript
// ── Arrays ──────────────────────────────
arr.map(x => x * 2)
arr.filter(x => x > 0)
arr.reduce((acc, x) => acc + x, 0)
arr.find(x => x.id === 7); arr.some(f); arr.every(f)
arr.includes(3); arr.indexOf(3); arr.slice(1, 3)
arr.push(x); arr.pop(); arr.sort((a, b) => a - b)
[...new Set(arr)] // dedupe
// ── Objects ─────────────────────────────
Object.keys(o); Object.values(o); Object.entries(o)
JSON.stringify(o); JSON.parse(s)
// ── Async ───────────────────────────────
const res = await fetch(url);
const data = await res.json();
try { await risky(); } catch (e) { handle(e); }
await Promise.all([a(), b()]); // concurrent
setTimeout(() => {}, 1000);
// ── Classes ─────────────────────────────
class Dog {
#secret = "hidden"; // private field
constructor(name) { this.name = name; }
bark() { return `${this.name} says woof`; }
static create(n) { return new Dog(n); }
}
// ── DOM ─────────────────────────────────
document.querySelector(".btn")
document.querySelectorAll("li")
el.addEventListener("click", e => {})
el.textContent = "hi"; el.classList.toggle("on")