Variables & Types
| Syntax | Description |
const x = 1 | Block-scoped constant (cannot be reassigned) |
let y = 2 | Block-scoped variable (can be reassigned) |
var z = 3 | Function-scoped variable (avoid — use let/const) |
Data Types
| Type | Example | Check |
String | "hello" 'hi' `template` | typeof x === "string" |
Number | 42 3.14 NaN Infinity | typeof x === "number" |
BigInt | 9007199254740991n | typeof x === "bigint" |
Boolean | true false | typeof x === "boolean" |
null | null | x === null |
undefined | undefined | typeof x === "undefined" |
Symbol | Symbol("id") | typeof x === "symbol" |
Object | {} [] new Date() | typeof x === "object" |
Type Conversion
String(123)
Number("42")
Number("abc")
Boolean(0)
Boolean("")
Boolean(null)
Boolean("hello")
parseInt("42px")
parseFloat("3.14")
+"42"
Strings
| Method / Syntax | Description |
`Hello ${name}` | Template literal (interpolation) |
str.length | String length |
str.includes("abc") | Check if string contains substring |
str.startsWith("He") | Check if starts with |
str.endsWith("lo") | Check if ends with |
str.indexOf("l") | First index of substring (-1 if not found) |
str.slice(0, 5) | Extract substring (start, end) |
str.substring(0, 5) | Extract substring (no negative indices) |
str.replace("a", "b") | Replace first occurrence |
str.replaceAll("a", "b") | Replace all occurrences |
str.split(",") | Split into array |
str.trim() | Remove whitespace from both ends |
str.trimStart() | Remove whitespace from start |
str.toUpperCase() | Convert to uppercase |
str.toLowerCase() | Convert to lowercase |
str.padStart(5, "0") | Pad start to length 5 with "0" |
str.repeat(3) | Repeat string 3 times |
str.match(/regex/g) | Find all regex matches |
str.at(-1) | Last character (ES2022) |
Arrays
Create & Access
const arr = [1, 2, 3];
arr[0]
arr.at(-1)
arr.length
Array.isArray(arr)
Array.from("abc")
Array(5).fill(0)
Mutating Methods
| Method | Description |
push(item) | Add to end, return new length |
pop() | Remove from end, return removed item |
unshift(item) | Add to beginning |
shift() | Remove from beginning |
splice(i, n, ...items) | Remove n items at index i, insert items |
sort() | Sort in place (lexicographic by default) |
sort((a,b) => a - b) | Sort numbers ascending |
reverse() | Reverse in place |
fill(value, start, end) | Fill with value |
Non-Mutating Methods
| Method | Description |
map(fn) | Transform each element, return new array |
filter(fn) | Keep elements where fn returns true |
reduce(fn, init) | Accumulate into single value |
find(fn) | First element where fn returns true |
findIndex(fn) | Index of first match (-1 if none) |
some(fn) | True if any element passes test |
every(fn) | True if all elements pass test |
includes(val) | True if array contains value |
indexOf(val) | First index of value (-1 if not found) |
forEach(fn) | Execute fn for each element (no return) |
concat(arr2) | Merge arrays into new array |
slice(start, end) | Extract portion into new array |
flat(depth) | Flatten nested arrays |
flatMap(fn) | Map then flatten one level |
join(sep) | Join elements into string |
toSorted(fn) | Sort without mutating (ES2023) |
toReversed() | Reverse without mutating (ES2023) |
[1,2,3].map(x => x * 2)
[1,2,3,4].filter(x => x > 2)
[1,2,3].reduce((sum, x) => sum + x, 0)
[1,2,3].find(x => x > 1)
[...new Set([1,1,2,3])]
Objects
const obj = { name: "Alice", age: 30 };
obj.name
obj["name"]
obj?.address?.city
obj.email = "a@b.com";
delete obj.age;
| Method | Description |
Object.keys(obj) | Array of keys |
Object.values(obj) | Array of values |
Object.entries(obj) | Array of [key, value] pairs |
Object.assign(target, src) | Copy properties (shallow) |
Object.freeze(obj) | Prevent modifications |
Object.fromEntries(arr) | Create object from [key, value] pairs |
"key" in obj | Check if key exists |
obj.hasOwnProperty("key") | Check own property (not inherited) |
{...obj, newKey: val} | Spread into new object (shallow copy + add) |
structuredClone(obj) | Deep clone (ES2022) |
Map & Set
const map = new Map();
map.set("key", "value");
map.get("key");
map.has("key");
map.delete("key");
map.size;
const set = new Set([1, 2, 2, 3]);
set.add(4);
set.has(2);
set.delete(2);
set.size;
[...set]
Functions
function add(a, b) { return a + b; }
const add = function(a, b) { return a + b; };
const add = (a, b) => a + b;
const greet = name => `Hello, ${name}!`;
const getObj = () => ({ key: "value" });
function greet(name = "World") { return `Hi ${name}`; }
function sum(...nums) { return nums.reduce((a, b) => a + b, 0); }
(() => { console.log("runs now"); })();
Tip: Arrow functions don't have their own this — they inherit it from the enclosing scope. Use regular functions for object methods and class methods.
Destructuring & Spread
const [a, b, ...rest] = [1, 2, 3, 4];
const { name, age, city = "NYC" } = person;
const { name: fullName } = person;
const { address: { city } } = person;
const arr2 = [...arr1, 4, 5];
const obj2 = { ...obj1, key: "val" };
function greet({ name, age }) {
return `${name} is ${age}`;
}
Control Flow
const status = age >= 18 ? "adult" : "minor";
const val = input ?? "default";
const val = input || "default";
isValid && doSomething();
user?.address?.city
arr?.[0]
fn?.()
for (const item of array) { }
for (const key in object) { }
switch (action) {
case "start": start(); break;
case "stop": stop(); break;
default: idle();
}
try {
riskyOperation();
} catch (err) {
console.error(err.message);
} finally {
cleanup();
}
DOM Manipulation
| Method | Description |
document.getElementById("id") | Select by ID |
document.querySelector(".class") | Select first match (CSS selector) |
document.querySelectorAll("p") | Select all matches (NodeList) |
el.textContent = "text" | Set text content |
el.innerHTML = "<b>html</b>" | Set HTML content |
el.setAttribute("href", url) | Set attribute |
el.getAttribute("href") | Get attribute |
el.classList.add("active") | Add CSS class |
el.classList.remove("active") | Remove CSS class |
el.classList.toggle("active") | Toggle CSS class |
el.classList.contains("active") | Check if class exists |
el.style.color = "red" | Set inline style |
document.createElement("div") | Create element |
parent.appendChild(child) | Append child element |
parent.removeChild(child) | Remove child element |
el.remove() | Remove element from DOM |
el.closest(".class") | Find nearest ancestor matching selector |
Events
el.addEventListener("click", (e) => {
e.preventDefault();
e.stopPropagation();
e.target
e.currentTarget
});
document.querySelector("ul").addEventListener("click", (e) => {
if (e.target.matches("li")) {
handleClick(e.target);
}
});
Async / Promises
const p = new Promise((resolve, reject) => {
resolve("done");
});
p.then(val => console.log(val))
.catch(err => console.error(err))
.finally(() => cleanup());
async function fetchData() {
try {
const res = await fetch("/api/data");
const data = await res.json();
return data;
} catch (err) {
console.error(err);
}
}
const [a, b] = await Promise.all([fetchA(), fetchB()]);
const result = await Promise.race([fetchA(), timeout(5000)]);
const results = await Promise.allSettled([p1, p2, p3]);
Fetch API
const res = await fetch("/api/users");
const users = await res.json();
const res = await fetch("/api/users", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: "Alice" }),
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
Classes
class Animal {
#sound;
constructor(name, sound) {
this.name = name;
this.#sound = sound;
}
speak() {
return `${this.name} says ${this.#sound}`;
}
get info() { return `${this.name}`; }
static create(name) { return new Animal(name, "..."); }
}
class Dog extends Animal {
constructor(name) {
super(name, "Woof");
}
fetch(item) {
return `${this.name} fetches ${item}`;
}
}
Modules
export const PI = 3.14;
export function add(a, b) { return a + b; }
export default class App { }
import { PI, add } from "./math.js";
import App from "./App.js";
import { add as sum } from "./math.js";
import * as math from "./math.js";
const module = await import("./heavy.js");
Useful Patterns
function debounce(fn, ms) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), ms);
};
}
const sleep = ms => new Promise(r => setTimeout(r, ms));
await sleep(1000);
const rand = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
arr.sort(() => Math.random() - 0.5);
const grouped = Object.groupBy(items, item => item.category);
[...new Set(arr)]
Object.keys(obj).length === 0
JSON.stringify(obj)
JSON.stringify(obj, null, 2)
JSON.parse(str)