Variables & Types
Declarations
const PI = 3.14; // block-scoped, no reassign
let count = 0; // block-scoped, reassignable
count += 1;
// avoid: var (function-scoped, hoisted)
Primitives
typeof "hi" // "string"
typeof 42 // "number"
typeof 10n // "bigint"
typeof true // "boolean"
typeof undefined // "undefined"
typeof null // "object" (historic quirk)
typeof Symbol() // "symbol"
Equality & Coercion
| Expression | Result |
|---|---|
0 === "0" | false |
0 == "0" | true |
null == undefined | true |
NaN === NaN | false |
Rule of thumb
Use === and !== everywhere. Use Number.isNaN(x) to test for NaN.
Strings & Numbers
`Hi ${name}` // template literal
"abc".toUpperCase() // "ABC"
"a,b,c".split(",") // ["a","b","c"]
" x ".trim() // "x"
"hello".includes("ell") // true
"hello".slice(1, 3) // "el"
"5".padStart(3, "0") // "005"
Number("3.14") // 3.14
parseInt("42px", 10) // 42
(255).toString(16) // "ff"
(3.14159).toFixed(2) // "3.14"
Math.max(1, 9, 4) // 9
Math.round(2.5) // 3
Arrays
Higher-order methods
const a = [1, 2, 3, 4];
a.map(x => x * 2) // [2,4,6,8]
a.filter(x => x > 2) // [3,4]
a.reduce((s, x) => s + x, 0) // 10
a.find(x => x === 3) // 3
a.some(x => x > 3) // true
a.every(x => x > 0) // true
a.flatMap(x => [x, x]) // [1,1,2,2,...]
Mutation & copying
a.push(5); a.pop(); // end
a.unshift(0); a.shift(); // start
[...a, 5] // spread copy + append
a.toSorted((x, y) => x - y) // non-mutating sort
a.includes(2) // true
Array.from({ length: 3 }, (_, i) => i) // [0,1,2]
Objects & Destructuring
const u = { id: 1, name: "Ada" };
const { name, role = "guest" } = u; // destructure + default
const merged = { ...u, active: true }; // spread copy
const [first, ...rest] = [1, 2, 3]; // array destructure
Object.keys(u) // ["id","name"]
Object.values(u) // [1,"Ada"]
Object.entries(u) // [["id",1],["name","Ada"]]
Object.assign({}, u)
structuredClone(u) // deep clone
Object.groupBy(arr, x => x.type) // ES2024
Functions & Closures
function add(a, b = 0) { return a + b; }
const mul = (a, b) => a * b; // arrow
const sum = (...nums) => nums.reduce((s, n) => s + n, 0);
// Closure: remembers outer scope
function counter() {
let n = 0;
return () => ++n;
}
const next = counter();
next(); next(); // 1, 2
// Optional chaining + nullish
obj?.a?.b ?? "default";
Classes
class Animal {
#hp = 100; // private field
constructor(name) { this.name = name; }
get hp() { return this.#hp; }
speak() { return `${this.name}...`; }
static of(name) { return new Animal(name); }
}
class Dog extends Animal {
speak() { return `${super.speak()} woof`; }
}
new Dog("Rex") instanceof Animal; // true
Async & Promises
async function main() {
try {
const res = await fetch("/api");
const data = await res.json();
return data;
} catch (err) {
console.error(err);
}
}
await Promise.all([p1, p2]); // all resolve (or reject)
await Promise.allSettled([p1, p2]); // never rejects
await Promise.race([p1, p2]); // first to settle
await Promise.any([p1, p2]); // first to fulfill
Promise.resolve(1).then(v => v + 1);
Event loop order
Sync code → all microtasks (.then/await) → one macrotask (setTimeout) → repeat.
DOM & Fetch
const el = document.querySelector(".card");
document.querySelectorAll("li");
el.textContent = "Hi";
el.classList.toggle("active");
el.addEventListener("click", (e) => e.preventDefault());
const node = document.createElement("div");
el.append(node);
// Fetch with options
const res = await fetch("/api/users", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: "Ada" }),
});
if (!res.ok) throw new Error(res.status);
const data = await res.json();
Map, Set & JSON
const s = new Set([1, 2, 2]); // {1,2}
s.has(1); s.add(3); s.size;
const m = new Map();
m.set("k", 1).get("k"); m.has("k");
for (const [k, v] of m) { /* ... */ }
JSON.stringify({ a: 1 }) // '{"a":1}'
JSON.parse('{"a":1}') // { a: 1 }
Modules
// export
export const x = 1;
export function f() {}
export default class {}
// import
import Default, { x, f } from "./mod.js";
import * as mod from "./mod.js";
const lazy = await import("./mod.js"); // dynamic
Tooling Commands
npm init -y # create package.json
npm install <pkg> # add dependency
npm run <script> # run package script
npx vitest # run tests
npx eslint . # lint
npx prettier --write . # format
node app.js # run a file
npm outdated # check for updates