JavaScript
Lessons, JS concept cards, and Array/Object/String method cheatsheets — all in one scrollable track. · 455 items · 50 lessons · click a card to expand
Lessons first, then JS Concepts and Methods cheatsheets below.
Runtime & execution context
4 items01How JavaScript runs: engine, runtime, and call stack
setTimeout and fetch that the engine does not provide on its own.RangeError: Maximum call stack size exceeded.function a() {
console.log("a start");
b();
console.log("a end");
}
function b() {
console.log("b");
}
a();
// Output order: a start → b → a endThe runtime environment (browser or Node.js) wraps the engine. The browser adds the DOM, window, fetch, and timers; Node adds fs, process, and its own event loop integration. Your JS never talks to the network or filesystem directly — it calls runtime APIs, which delegate to the OS.
02Execution context, hoisting, and the temporal dead zone
var declarations are hoisted and initialized as undefined; let and const are hoisted but sit in the temporal dead zone until their declaration line executes.this) and execution (run code line by line). During creation, var bindings exist immediately with value undefined. let/const bindings exist but are inaccessible — accessing them throws ReferenceError.console.log(greet); // undefined (not ReferenceError)
var greet = "hello";
console.log(count); // ReferenceError — TDZ
let count = 0;
function demo() {
console.log(x); // undefined
var x = 10;
// console.log(y); // ReferenceError
let y = 20;
}Function declarations are fully hoisted (name + body), which is why you can call foo() before its declaration in the same scope. Function expressions assigned to var follow var hoisting rules — only the name is hoisted, not the assignment.
let and const by default. Use const unless you need to reassign the binding. This avoids hoisting surprises and makes intent clearer.var, let, and a function declaration before running it. Then refactor to use only const/let and confirm behavior is unchanged.03Scope chain and lexical (static) scope
{} with let/const), functions, and modules. When the engine looks up name, it checks the current scope, then the parent, then the parent of that, until it reaches the global object or throws ReferenceError.const theme = "dark";
function makeButton(label) {
const prefix = "[UI]";
return function render() {
return `${prefix} ${label} (${theme})`;
};
}
const btn = makeButton("Save");
console.log(btn()); // "[UI] Save (dark)"
// `prefix`, `label`, and `theme` are still reachable via closureThis is lexical scoping: render closes over variables from makeButton's scope and the global scope. Changing theme after creating btn affects the next call because the closure holds a live binding, not a snapshot (for let/const/var variables — not for primitive parameters copied at call time unless they're objects).
createCounter(start) that returns { increment, getValue } without using a class. Verify two counters do not share state.04Strict mode and global vs module scope
'use strict' enables stricter parsing and runtime checks. Modules and class bodies run in strict mode automatically. In sloppy mode, assigning to an undeclared variable creates a global property; in strict mode it throws.delete of non-configurable properties, and this defaulting to undefined in plain functions instead of the global object."use strict";
function sloppy() {
// In non-strict: creates window.leaked = 1 in browsers
// leaked = 1; // ReferenceError in strict mode
}
function showThis() {
console.log(this); // undefined (strict), not window
}
showThis();ES modules (<script type="module"> or import in Node) have their own top-level scope — top-level const is not attached to window. Each module is evaluated once and exports live bindings.
// math.js
export const PI = 3.14159;
export function area(r) { return PI * r * r; }
// app.js
import { area } from "./math.js";
console.log(area(2));this-as-window behavior.type="module" HTML setup. Confirm top-level variables are not on window.Types & coercion
4 items05Primitives vs objects: typeof and value categories
undefined, null, boolean, number, bigint, string, symbol) and one object type (including arrays, functions, dates). Primitives are immutable; objects are mutable references.typeof is quick but imperfect: typeof null === "object" is a long-standing bug; functions report "function" even though they are objects.typeof undefined; // "undefined"
typeof "hi"; // "string"
typeof 42; // "number"
typeof true; // "boolean"
typeof Symbol(); // "symbol"
typeof 10n; // "bigint"
typeof null; // "object" (historical quirk)
typeof {}; // "object"
typeof []; // "object"
typeof (() => {}); // "function"Primitives are stored by value — copying assigns the value. Objects are stored by reference — copying copies the pointer, so mutating through either variable affects the same object.
let a = { n: 1 };
let b = a;
b.n = 2;
console.log(a.n); // 2 — same objectArray.isArray(x), x === null, or Object.prototype.toString.call(x) when you need precise type checks beyond typeof.describe(value) that returns a human-readable type string distinguishing null, arrays, plain objects, and primitives.06Truthy, falsy, and explicit coercion
true or false. Falsy values are false, 0, -0, 0n, "", null, undefined, and NaN. Everything else is truthy — including [], {}, and "0".if, while, !, &&, ||, and the ternary operator. Explicit conversion uses Boolean(), !!, Number(), String(), or BigInt().if ("") console.log("never"); // empty string is falsy
if ("0") console.log("runs"); // non-empty string is truthy
console.log(Boolean([])); // true
console.log(Boolean({})); // true
console.log(Number("42")); // 42
console.log(Number("")); // 0
console.log(String(null)); // "null"Abstract equality (==) applies coercion rules (avoid in production). Strict equality (===) compares type and value without conversion.
0 == false; // true (coercion)
0 === false; // false
null == undefined; // true
null === undefined; // false=== and !== by default. When accepting user input, coerce explicitly at boundaries (forms, APIs) rather than relying on implicit rules deep in logic.toBool(input) helper that treats "false", "0", and "" as false but preserves real booleans. Write three test cases.07Number quirks: NaN, Infinity, and floating-point
NaN is not equal to anything including itself; use Number.isNaN. Decimal math can surprise you — use rounding strategies or integers (cents) for money.0.1 + 0.2; // 0.30000000000000004
Number.isNaN(NaN); // true
NaN === NaN; // false
Number.isNaN("x"); // false — does not coerce
isNaN("x"); // true — coerces first (avoid)
Number.MAX_SAFE_INTEGER; // 9007199254740991
9007199254740992 === 9007199254740992 + 1; // true — precision lostparseInt("42px", 10) parses leading digits; Number("42px") yields NaN. Always pass radix 10 to parseInt unless you intentionally parse octal/hex.
Number.EPSILON or Math.abs(a - b) < epsilon for floats.roundMoney(n) that rounds a dollar float to two decimal places reliably. Test with 0.1 + 0.2 and 1.005.08Equality deep dive: SameValue and object identity
=== uses SameValue equality for primitives. Objects are equal only if they are the same reference. To compare structure, you must compare properties (shallow or deep) or serialize — never === alone.const a = { x: 1 };
const b = { x: 1 };
const c = a;
a === b; // false — different objects
a === c; // true — same reference
Object.is(NaN, NaN); // true (SameValue)
Object.is(+0, -0); // false
+0 === -0; // true (=== treats them equal)Shallow compare checks top-level keys:
function shallowEqual(obj1, obj2) {
const keys1 = Object.keys(obj1);
const keys2 = Object.keys(obj2);
if (keys1.length !== keys2.length) return false;
return keys1.every((key) => Object.is(obj1[key], obj2[key]));
}shallowEqual and verify it returns true for { a: 1, b: [2] } vs a copy with the same array reference but false when the nested array is cloned.Functions & closures
5 items09Function declarations, expressions, and arrow functions
this and cannot be used as constructors. Choose based on hoisting needs, this behavior, and readability.// Declaration — hoisted
log("hi");
function log(msg) { console.log(msg); }
// Expression
const multiply = function (a, b) { return a * b; };
// Arrow — concise, lexical this
const nums = [1, 2, 3];
const doubled = nums.map((n) => n * 2);
const counter = {
count: 0,
inc() {
setTimeout(() => {
this.count++; // `this` is counter (lexical from inc)
}, 0);
},
};Arrows have no arguments object (use rest ...args). They cannot be newed. For object methods that need dynamic this, use shorthand method syntax (inc() {}), not arrows.
setTimeout callback that incorrectly uses this with a regular function into an arrow inside a method and confirm this.count increments.10Parameters: defaults, rest, and spread
undefined. Rest collects remaining arguments into an array; spread expands iterables into individual elements. Both are essential for flexible APIs.function greet(name = "Guest", punctuation = "!") {
return `Hello, ${name}${punctuation}`;
}
greet(undefined, "?"); // "Hello, Guest?"
function sum(...nums) {
return nums.reduce((total, n) => total + n, 0);
}
sum(1, 2, 3); // 6
const defaults = { theme: "light", lang: "en" };
const user = { lang: "fr" };
const config = { ...defaults, ...user, theme: "dark" };
// { theme: "dark", lang: "fr" } — later keys winRest must be the last formal parameter. Spread works on arrays, strings, and any iterable in array literals, object literals (shallow clone/merge), and function calls.
arguments in modern code — it's real array-like and works in arrow functions.clamp(value, min, max) with default min = 0, max = 100, then a wrapper clampPositive(...values) that clamps each argument using spread.11Closures: private state and factory functions
function createWallet(initial) {
let balance = initial; // private to the closure
return {
deposit(amount) {
balance += amount;
return balance;
},
withdraw(amount) {
if (amount > balance) throw new Error("Insufficient funds");
balance -= amount;
return balance;
},
getBalance() {
return balance;
},
};
}
const wallet = createWallet(100);
wallet.deposit(50); // 150
wallet.withdraw(30); // 120
// wallet.balance — undefined; not exposedClosures in loops were historically tricky with var:
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 0); // 0, 1, 2 — new binding per iteration
}let in each iteration). Watch memory: long-lived callbacks closing over large objects can prevent garbage collection.once(fn) function that runs fn only on the first call and returns the same result thereafter.12Higher-order functions: map, filter, reduce
map, filter, and reduce express data transformations declaratively and chain cleanly.const products = [
{ name: "Pen", price: 1.5, qty: 10 },
{ name: "Notebook", price: 4, qty: 3 },
{ name: "Stapler", price: 8, qty: 1 },
];
const inventoryValue = products
.filter((p) => p.qty > 0)
.map((p) => ({ ...p, total: p.price * p.qty }))
.reduce((sum, p) => sum + p.total, 0);
console.log(inventoryValue); // 34.5reduce is the most general — it can implement map and filter. Always provide an initial accumulator when the type matters (numbers, objects, arrays).
const words = ["apple", "banana", "apricot"];
const byLetter = words.reduce((acc, word) => {
const letter = word[0];
acc[letter] = (acc[letter] ?? 0) + 1;
return acc;
}, {});
// { a: 2, b: 1 }for loops when transforming collections — intent is clearer. For very hot paths or early break, a for...of loop may still be appropriate.{ type: "credit"|"debit", amount }, compute net balance using a single reduce.13IIFE, recursion, and call stack discipline
// IIFE — avoid polluting global scope (less needed with modules)
const app = (function () {
const secret = "hidden";
return { getSecret: () => secret };
})();
function factorial(n) {
if (n <= 1) return 1; // base case
return n * factorial(n - 1);
}
factorial(5); // 120Tail call optimization is not guaranteed in all JS engines; deep recursion may fail. Convert to iteration when depth is unbounded:
function factorialIter(n) {
let result = 1;
for (let i = 2; i <= n; i++) result *= i;
return result;
}sumNested(array) where arrays may contain numbers or nested arrays, e.g. [1, [2, [3]], 4] → 10.this & prototypes
3 items14The four rules of this binding
this is determined by how a function is called, not where it is defined — except arrow functions, which inherit this lexically. Rules: default binding, implicit (method), explicit (call/apply/bind), and new binding.function show() {
console.log(this);
}
show(); // default: undefined (strict) or global
const user = {
name: "Ada",
greet() {
console.log(this.name);
},
};
user.greet(); // implicit: user
const greetFn = user.greet;
greetFn(); // default binding — lost context!
show.call({ id: 1 }); // explicit binding
function Person(name) {
this.name = name;
}
const p = new Person("Lin"); // new: fresh object as thisbind returns a new function with permanently bound this:
const boundGreet = user.greet.bind(user);
boundGreet(); // "Ada"const fn = obj.method) loses implicit binding — use bind, wrap in arrow inside the method, or call as obj.method().this. Break it by destructuring one method, then fix with bind.15Prototype chain and object creation patterns
[[Prototype]] (exposed as __proto__ or via Object.getPrototypeOf). Functions have a prototype property used when invoked with new. Classes are syntactic sugar over prototypes.const animal = {
speak() {
return `${this.name} makes a sound`;
},
};
const dog = Object.create(animal);
dog.name = "Rex";
dog.speak(); // "Rex makes a sound"
function Person(name) {
this.name = name;
}
Person.prototype.greet = function () {
return `Hi, I'm ${this.name}`;
};
const ada = new Person("Ada");
ada.greet(); // uses Person.prototypeClass syntax:
class Person {
constructor(name) {
this.name = name;
}
greet() {
return `Hi, I'm ${this.name}`;
}
}Methods on the prototype are shared; own properties live on the instance. hasOwnProperty checks own keys only; in checks the full chain.
class for readability today, but understand prototypes for debugging (instanceof, library code, and interview questions).Counter with (a) a factory + closures, (b) constructor + prototype, and (c) class. List trade-offs for each.16Inheritance, super, and composition over inheritance
extends and super wire this up in classes. Favor composition (has-a) when behavior mixing is simpler than deep inheritance trees.class Animal {
constructor(name) {
this.name = name;
}
speak() {
return `${this.name} speaks`;
}
}
class Dog extends Animal {
constructor(name, breed) {
super(name); // must call before using `this`
this.breed = breed;
}
speak() {
return `${super.speak()} — woof! (${this.breed})`;
}
}
const d = new Dog("Rex", "Lab");
d.speak();Composition example:
const canFly = {
fly() { return `${this.name} flies`; },
};
function createBird(name) {
return Object.assign({ name }, canFly);
}extends many levels.Employee and Manager where Manager has a list of reports. Use composition (reports array + delegate methods) rather than Manager extending Employee unless shared state truly warrants it.ES6+: destructuring, modules, iterators
4 items17Destructuring and shorthand object syntax
const [first, second, ...rest] = [10, 20, 30, 40];
// first 10, second 20, rest [30, 40]
const { name, age = 18, ...others } = { name: "Sam", city: "NYC" };
// name "Sam", age 18, others { city: "NYC" }
function printUser({ name, role = "guest" }) {
console.log(`${name} (${role})`);
}
const x = 1, y = 2;
const point = { x, y }; // shorthand propertySwap without a temp variable:
let a = 1, b = 2;
[a, b] = [b, a];Nested destructuring works but keep it readable — extract in steps for deeply nested API JSON.
normalizeUser(raw) that destructures { data: { id, attributes: { email, name } } } with defaults and returns a flat { id, email, name }.18ES modules: import, export, and live bindings
let, importers see the new value.// logger.js
export const levels = ["info", "warn", "error"];
export function log(level, msg) {
console.log(`[${level}] ${msg}`);
}
export default function createLogger(prefix) {
return (msg) => log("info", `${prefix}: ${msg}`);
}
// app.js
import createLogger, { log, levels } from "./logger.js";
import * as Logger from "./logger.js"; // namespace object
const info = createLogger("APP");
info("started");Dynamic import returns a promise — useful for code splitting:
const module = await import("./heavy-chart.js");
module.renderChart(data);constants.js, math.js, and main.js. Use both named and default exports and verify live binding by exporting a counter incremented from one file and read from another.19Iterators, iterables, and for...of
Symbol.iterator returning an iterator. An iterator has next() returning { value, done }. for...of, spread, and destructuring consume iterables.const range = {
from: 1,
to: 3,
[Symbol.iterator]() {
let current = this.from;
const last = this.to;
return {
next() {
if (current <= last) {
return { value: current++, done: false };
}
return { done: true };
},
};
},
};
for (const n of range) console.log(n); // 1, 2, 3
console.log([...range]); // [1, 2, 3]Built-in iterables: arrays, strings, maps, sets, and arguments. Plain objects are not iterable unless you define Symbol.iterator.
Generators (function*) are a concise way to create iterators:
function* ids() {
let id = 1;
while (true) yield id++;
}
const gen = ids();
gen.next(); // { value: 1, done: false }LinkedList class that supports for...of over its values without exposing internal nodes publicly.20Symbols, Map, Set, and structured data choices
Symbol creates unique property keys — useful for meta-data and avoiding name clashes. Map and Set provide better semantics than plain objects/arrays for keyed collections and uniqueness, especially with non-string keys.const ID = Symbol("id");
const user = { name: "Lee", [ID]: 42 };
Object.keys(user); // ["name"] — symbols omitted
const map = new Map();
map.set({ k: 1 }, "metadata"); // object keys OK
map.get({ k: 1 }); // undefined — different object reference
const set = new Set([1, 2, 2, 3]);
[...set]; // [1, 2, 3]
// WeakMap keys must be objects — useful for private caches tied to object lifetime
const cache = new WeakMap();
function expensive(obj) {
if (cache.has(obj)) return cache.get(obj);
const result = Object.keys(obj).length;
cache.set(obj, result);
return result;
}Map when keys are unknown strings or you need frequent add/delete with size tracking. Use plain objects for JSON-serializable records with fixed shape.id using a Map, preserving first occurrence order.Async: promises, async/await, event loop
5 items21Synchronous vs asynchronous code and the event loop
console.log("1");
setTimeout(() => console.log("2"), 0);
Promise.resolve().then(() => console.log("3"));
console.log("4");
// Order: 1, 4, 3, 2Microtasks (promise callbacks, queueMicrotask) run before the next macrotask (timers, I/O). That is why 3 prints before 2 even though both are "async."
The loop in plain language:
- Run synchronous code until the stack clears.
- Drain all microtasks.
- Take one macrotask (e.g. timer callback).
- Repeat.
requestAnimationFrame, setTimeout(0), or Web Workers).setTimeout, promises, and synchronous logs. Verify in Node and the browser — order should match for this example.22Callbacks, callback hell, and error-first conventions
(err, data) => {}. Deep nesting ("callback hell") hurts readability — promises and async/await improve structure, but callbacks remain at the runtime boundary.function fetchUser(id, callback) {
setTimeout(() => {
if (id <= 0) return callback(new Error("Invalid id"));
callback(null, { id, name: "User" + id });
}, 100);
}
fetchUser(1, (err, user) => {
if (err) return console.error(err);
fetchUser(user.id + 1, (err2, user2) => {
if (err2) return console.error(err2);
console.log(user, user2);
});
});Promises flatten nesting:
function fetchUserAsync(id) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (id <= 0) reject(new Error("Invalid id"));
else resolve({ id, name: "User" + id });
}, 100);
});
}
fetchUserAsync(1)
.then((user) => fetchUserAsync(user.id + 1))
.then(console.log)
.catch(console.error);util.promisify in Node or a small helper) and use async/await everywhere else.readFile(path, cb) callback API in a readFileAsync promise and load two files sequentially with async/await.23Promises: states, chaining, and combinators
.then handles fulfillment, .catch handles rejection, .finally runs either way. Promise.all, race, allSettled, and any coordinate multiple async operations.const p = new Promise((resolve, reject) => {
resolve(42);
});
p.then((value) => value * 2)
.then((value) => {
throw new Error("oops");
})
.catch((err) => {
console.error(err.message);
return "recovered";
})
.finally(() => console.log("cleanup"));Combinators:
const a = Promise.resolve(1);
const b = Promise.resolve(2);
Promise.all([a, b]); // [1, 2] — fails fast if one rejects
Promise.allSettled([a, b]); // [{status:"fulfilled",...}, ...]
Promise.race([a, b]); // first settled
Promise.any([Promise.reject(1), b]); // first fulfilled.then returns a new promise, enabling chains. Returning a value wraps it; returning a promise adopts its fate.
.then handlers when starting async work — forgetting return breaks chains silently.Promise.allSettled, then log which succeeded and which failed without try/catch around the whole batch.24async/await and structured concurrency
async functions always return a promise. await pauses within an async function until a promise settles, writing async code that reads synchronously. Use try/catch for errors and Promise.all for parallel independent work.async function loadDashboard(userId) {
try {
const user = await fetchUserAsync(userId);
const [posts, notifications] = await Promise.all([
fetchPostsAsync(user.id),
fetchNotificationsAsync(user.id),
]);
return { user, posts, notifications };
} catch (err) {
console.error("Dashboard failed:", err.message);
throw err;
}
}Sequential vs parallel:
// Sequential — slower
const a = await step1();
const b = await step2();
// Parallel — independent steps
const [a2, b2] = await Promise.all([step1(), step2()]);Top-level await works in modules:
// config.js
export const settings = await fetch("/api/settings").then((r) => r.json());Promise.all(items.map(async ...)) when operations are independent.retry(fn, times) that awaits an async function and retries on failure up to times, with a 200ms delay between attempts.25Microtasks, macrotasks, and async debugging
setTimeout(0) interleaving. Async debugging means reading stack traces, logging with labels, and breaking on uncaught promise rejections.async function a() {
console.log("a start");
await null; // yields to microtask queue
console.log("a end");
}
console.log("sync");
a();
console.log("sync end");
// sync → a start → sync end → a endawait schedules continuation as a microtask. Nested async functions add layers but still respect microtask draining before timers.
Debugging tips:
// Label logs
console.log("[fetchUser]", userId);
// Break on uncaught exceptions in DevTools
// Sources → pause on uncaught exceptions
// Unhandled rejection
process.on("unhandledRejection", console.error); // Node
window.addEventListener("unhandledrejection", (e) => {
console.error(e.reason);
});await.await Promise.resolve() between each and diagram which logs are sync vs microtask.DOM & events
3 items26Selecting and updating the DOM
querySelector / querySelectorAll for selection, textContent / innerHTML (carefully) for content, and classList / dataset for attributes and state.const app = document.querySelector("#app");
const items = document.querySelectorAll(".item");
app.textContent = "Hello"; // safe — no HTML parsing
// app.innerHTML = userInput; // risky — XSS if unsanitized
const btn = document.createElement("button");
btn.textContent = "Click me";
btn.classList.add("primary");
btn.dataset.action = "save";
app.append(btn);
items.forEach((el) => {
el.classList.toggle("active", el.dataset.id === "1");
});Prefer document.createElement and append over concatenating HTML strings for dynamic UI. When you must parse HTML, sanitize untrusted input.
{ id, text, done }[], clear #list and render <li> elements with a done class toggle — no framework.27Events: bubbling, delegation, and preventDefault
event.target to handle children — ideal for dynamic lists. preventDefault stops default browser behavior; stopPropagation stops further propagation.const list = document.querySelector("#list");
list.addEventListener("click", (event) => {
const item = event.target.closest("[data-id]");
if (!item || !list.contains(item)) return;
const id = item.dataset.id;
console.log("Clicked item", id);
});
const form = document.querySelector("#form");
form.addEventListener("submit", (event) => {
event.preventDefault();
const data = new FormData(form);
console.log(Object.fromEntries(data));
});Use { capture: true } for capture phase (root → target). { once: true } auto-removes after one fire. Passive listeners improve scroll performance when you won't call preventDefault.
document, #app) for lists that re-render. Compare event.target (deepest element) vs event.currentTarget (element with listener).#toolbar should log which button was pressed even after buttons are replaced.28Timers, requestAnimationFrame, and browser APIs
setTimeout and setInterval schedule macrotasks. requestAnimationFrame syncs work to display refreshes (~60fps) — best for animations. Modern browsers expose rich APIs: fetch, localStorage, IntersectionObserver, and more.// Debounced resize handler pattern
let resizeTimer;
window.addEventListener("resize", () => {
clearTimeout(resizeTimer);
resizeTimer = setTimeout(() => {
console.log("layout recalc", window.innerWidth);
}, 150);
});
// Animation
let start;
function frame(timestamp) {
if (!start) start = timestamp;
const progress = Math.min((timestamp - start) / 1000, 1);
box.style.transform = `translateX(${progress * 200}px)`;
if (progress < 1) requestAnimationFrame(frame);
}
requestAnimationFrame(frame);
// Storage
localStorage.setItem("theme", "dark");
localStorage.getItem("theme");fetch returns a promise for HTTP:
const res = await fetch("/api/users");
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const users = await res.json();rAF over setInterval for visual updates — it pauses in background tabs and aligns with paint.requestAnimationFrame, stopping after 2 seconds. Log frame count.Errors & debugging
2 items29Throwing, catching, and custom errors
throw to signal exceptional conditions. try/catch/finally handles errors locally; uncaught errors propagate until they crash the thread or trigger global handlers. Custom error classes add name and context for clearer debugging.class ValidationError extends Error {
constructor(field, message) {
super(message);
this.name = "ValidationError";
this.field = field;
}
}
function parseAge(input) {
const age = Number(input);
if (Number.isNaN(age)) throw new ValidationError("age", "Must be a number");
if (age < 0 || age > 130) throw new ValidationError("age", "Out of range");
return age;
}
try {
parseAge("abc");
} catch (err) {
if (err instanceof ValidationError) {
console.error(`Invalid ${err.field}: ${err.message}`);
} else {
throw err; // rethrow unknown errors
}
} finally {
console.log("attempt finished");
}Distinguish operational errors (expected, handle gracefully) from programmer errors (bugs — fix code). Don't catch everything and swallow silently.
cause (ES2022): throw new Error("Failed to save", { cause: err }).assert(condition, message) that throws an AssertionError subclass. Use it in a small validator for email format.30Debugging workflow: breakpoints, logging, and DevTools
console methods, breakpoints, and network inspection — not random console.log everywhere.const user = { id: 1, roles: ["admin"] };
console.log("user", user);
console.table(user.roles.map((r) => ({ role: r })));
console.time("fetch");
await fetch("/api/data");
console.timeEnd("fetch");
console.assert(user.id > 0, "user id must be positive");
// Conditional breakpoint in DevTools: right-click line number → add condition
// e.g. id === 42Workflow:
- Reproduce reliably with minimal input.
- Form a hypothesis (wrong value, timing, scope).
- Inspect with breakpoint or targeted log.
- Fix and add a regression test or guard.
Network tab shows fetch status, payload, and timing. Sources tab shows async stack traces for promises when supported.
debugger; statement to pause when DevTools is open — faster than hunting line numbers during active investigation.NaN for some inputs. Find the bad path using one conditional breakpoint and document the fix in a comment.Practical patterns: debounce, deep clone, curry
5 items31Debounce and throttle
function debounce(fn, wait) {
let timerId;
return function debounced(...args) {
clearTimeout(timerId);
timerId = setTimeout(() => fn.apply(this, args), wait);
};
}
function throttle(fn, limit) {
let inThrottle = false;
return function throttled(...args) {
if (inThrottle) return;
fn.apply(this, args);
inThrottle = true;
setTimeout(() => { inThrottle = false; }, limit);
};
}
const onSearch = debounce((query) => {
console.log("API search:", query);
}, 300);
const onScroll = throttle(() => {
console.log("scroll position", window.scrollY);
}, 200);Debounce trailing edge (above) fires after typing pauses. Leading-edge debounce fires immediately then waits — useful for button double-submit guards.
.cancel() if you add one) to avoid setState on unmounted components in React.<input> and log API calls — confirm rapid typing produces one log after pause, not one per keystroke.32Deep clone vs shallow copy
structuredClone (modern) handles most cases; JSON round-trip loses types and skips functions, undefined, and cycles.const original = {
name: "Ada",
tags: ["dev", "math"],
meta: { active: true },
};
const shallow = { ...original };
shallow.tags.push("new");
original.tags.length; // 3 — shared array
const deep = structuredClone(original);
deep.tags.push("clone-only");
original.tags.length; // still 3
// Manual deep clone (simplified — no cycles, no Map/Set)
function deepClone(value) {
if (value === null || typeof value !== "object") return value;
if (Array.isArray(value)) return value.map(deepClone);
return Object.fromEntries(
Object.entries(value).map(([k, v]) => [k, deepClone(v)])
);
}JSON limitations:
JSON.parse(JSON.stringify({ d: new Date(), fn: () => {} }));
// Date becomes string, fn omitted{...obj}, structuredClone, and JSON clone. List which fields still alias the original.33Currying and partial application
f(a,b,c) into f(a)(b)(c). Partial application fixes some arguments upfront. Both create specialized functions from general ones — useful for configuration and reusable pipelines.// Curried add
const add = (a) => (b) => a + b;
const add5 = add(5);
add5(3); // 8
function curry(fn) {
return function curried(...args) {
if (args.length >= fn.length) return fn.apply(this, args);
return (...next) => curried.apply(this, args.concat(next));
};
}
const multiply = (a, b, c) => a * b * c;
const curriedMultiply = curry(multiply);
curriedMultiply(2)(3)(4); // 24
curriedMultiply(2, 3)(4); // 24
// Partial application
const partial = (fn, ...fixed) => (...rest) => fn(...fixed, ...rest);
const greet = (greeting, name) => `${greeting}, ${name}`;
const sayHello = partial(greet, "Hello");
sayHello("Sam"); // "Hello, Sam"fetchWithBase(baseUrl)(path)(options) helper and create fetchApi preset with your API base URL.34Memoization and caching function results
function memoize(fn, keyFn = (...args) => JSON.stringify(args)) {
const cache = new Map();
return function memoized(...args) {
const key = keyFn(...args);
if (cache.has(key)) return cache.get(key);
const result = fn.apply(this, args);
cache.set(key, result);
return result;
};
}
const fib = memoize(function fib(n) {
if (n <= 1) return n;
return fib(n - 1) + fib(n - 2);
});
fib(50); // fast with cacheFor single-argument primitives, a plain object or Map works. For multiple args or object params, define a stable keyFn. Clear cache when inputs change externally.
isPrime(n) and time isPrime(10007) twice with console.time. Add cache size logging.35Piping, composition, and small utility design
const pipe =
(...fns) =>
(value) =>
fns.reduce((acc, fn) => fn(acc), value);
const trim = (s) => s.trim();
const lower = (s) => s.toLowerCase();
const slugify = (s) => s.replace(/\s+/g, "-");
const toSlug = pipe(trim, lower, slugify);
toSlug(" Hello World "); // "hello-world"
// compose — right to left
const compose =
(...fns) =>
(value) =>
fns.reduceRight((acc, fn) => fn(acc), value);
const normalizeUser = pipe(
(raw) => ({ ...raw, name: raw.name ?? "Anonymous" }),
(u) => ({ ...u, name: u.name.trim() }),
(u) => ({ ...u, handle: toSlug(u.name) })
);
normalizeUser({ name: " Ada Lovelace " });
// { name: "Ada Lovelace", handle: "ada-lovelace" }Design guidelines for utilities:
- One clear responsibility per function.
- Pure when possible; isolate side effects at boundaries.
- Name for intent (
toSlug, notprocessString). - Test edge cases: empty input, null, large data.
pipe/compose lines often suffice without importing a library.processTransaction(tx) pipeline that validates amount > 0, applies a 2% fee, rounds money, and returns a receipt object — each step a separate pure function composed with pipe.Dates and time
4 items36Date model
Date is a timestamp: milliseconds since the Unix epoch (1970-01-01T00:00:00.000Z), stored as UTC internally, displayed in the local timezone unless you ask otherwise.new Date() captures "now." new Date(ms) wraps a number. new Date("2026-09-08") parses an ISO date as UTC midnight. new Date("2026-09-08T12:00:00") without a Z or offset is treated as local time. That split is the source of most "off by one day" bugs: a date-only string becomes the previous calendar day in US timezones.const now = new Date();
now.getTime(); // ms since epoch
Date.now(); // same, without allocating a Date
const fromIso = new Date("2026-09-08T09:46:00.000Z");
fromIso.toISOString(); // always UTC: "2026-09-08T09:46:00.000Z"
fromIso.getFullYear(); // local calendar year
fromIso.getUTCFullYear(); // UTC calendar year
// Date-only ISO is UTC midnight — may be "yesterday" locally
const dateOnly = new Date("2026-09-08");
dateOnly.toISOString(); // "2026-09-08T00:00:00.000Z"
dateOnly.getDate(); // 7 or 8 depending on local offset
// Local components (0-based month!)
const d = new Date(2026, 8, 8, 9, 46, 0); // Sep 8, 2026 09:46 local
d.getMonth(); // 8
d.getDate(); // 8Getters come in pairs: getHours / getUTCHours, getDate / getUTCDate. Mixing them silently shifts the clock. Invalid Date is a Date whose getTime() is NaN — new Date("not a date") does not throw. Always check Number.isNaN(date.getTime()) before formatting or doing math.
"YYYY-MM-DD" strings and parse them yourself into local midnight (new Date(y, m - 1, day)). Do not round-trip date-only values through Date + toISOString().new Date("2026-01-01") and new Date(2026, 0, 1) in your timezone. Explain why getDate() can differ. Write isValidDate(value) that returns false for Invalid Date.37Intl formatting
Intl.DateTimeFormat, Intl.NumberFormat, and Intl.RelativeTimeFormat format dates, money, and relative time for a locale — without rolling your own month names or currency symbols.Date object does not know about locales. toLocaleString() is a thin wrapper; constructing Intl.DateTimeFormat once and calling format is faster in loops and lets you inspect resolvedOptions(). Pass a BCP 47 locale ("en-US", "hi-IN", "de-DE") and an options object for calendar fields, time zone, and hour cycle.const when = new Date("2026-09-08T09:46:00.000Z");
const dateFmt = new Intl.DateTimeFormat("en-IN", {
dateStyle: "medium",
timeStyle: "short",
timeZone: "Asia/Kolkata",
});
dateFmt.format(when); // e.g. "8 Sept 2026, 3:16 pm"
const parts = dateFmt.formatToParts(when);
// [{ type: "day", value: "8" }, { type: "literal", value: " " }, ...]
const money = new Intl.NumberFormat("en-IN", {
style: "currency",
currency: "INR",
});
money.format(1299.5); // "₹1,299.50"
const relative = new Intl.RelativeTimeFormat("en", { numeric: "auto" });
relative.format(-1, "day"); // "yesterday"
relative.format(2, "hour"); // "in 2 hours"formatToParts is the escape hatch for custom UI (wrap the day in a <strong>, style the currency symbol separately). Intl.NumberFormat also handles percent, unit ("kilometer"), and compact notation (1.2K). Never concatenate "$" + amount — currency placement and grouping differ by locale.
new Intl.DateTimeFormat on every render is wasteful; the constructor does locale data lookup.Date with timeZone: "UTC" and timeZone: "America/Los_Angeles". Then format 1999.99 as USD for "en-US" and "de-DE" and compare symbol placement.38Arithmetic and timezones
24 * 60 * 60 * 1000 to cross calendar days — DST makes some local days 23 or 25 hours long.Date is not a duration type. date.setDate(date.getDate() + 1) advances the calendar day in local time and is the correct way to say "tomorrow." Adding 86,400,000 ms can land on the same clock time on a different UTC day, or skip/repeat an hour when DST starts or ends. For "add 90 minutes," milliseconds (or setMinutes) are fine because you are adding a duration, not a calendar unit.function addDaysLocal(date, days) {
const next = new Date(date.getTime());
next.setDate(next.getDate() + days);
return next;
}
function addMillis(date, ms) {
return new Date(date.getTime() + ms);
}
function startOfLocalDay(date) {
return new Date(date.getFullYear(), date.getMonth(), date.getDate());
}
function diffInDaysUTC(a, b) {
const MS_PER_DAY = 86_400_000;
const utcA = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate());
const utcB = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate());
return Math.round((utcB - utcA) / MS_PER_DAY);
}
// Named zone offset at a specific instant (minutes)
function offsetMinutesInZone(date, timeZone) {
const parts = new Intl.DateTimeFormat("en-US", {
timeZone,
timeZoneName: "shortOffset",
}).formatToParts(date);
const tz = parts.find((p) => p.type === "timeZoneName")?.value ?? "GMT";
const match = tz.match(/GMT([+-])(\d{1,2})(?::(\d{2}))?/);
if (!match) return 0;
const sign = match[1] === "-" ? -1 : 1;
const hours = Number(match[2]);
const mins = Number(match[3] ?? 0);
return sign * (hours * 60 + mins);
}Timezones are political, not math. Asia/Kolkata is IST (UTC+5:30) with no DST. America/New_York switches. Intl can format in a named zone, but Date getters still use the host timezone. There is no date.getHours("Asia/Kolkata") — you read parts via Intl.DateTimeFormat + formatToParts, or convert with a library. Storing instants as ISO UTC (toISOString()) and converting only at the edges keeps servers and clients aligned.
"Europe/Berlin"). Display each side in their own zone.+ 86400000 and with setDate(getDate() + 1). Compare getHours(). Write startOfUtcDay(date) that returns 00:00:00.000Z.39When to use a library
Date, Intl, Temporal when available) for display and simple math; reach for a library when you do recurring events, fiscal calendars, or serious timezone conversion.Date is enough for "show this timestamp in the user's locale," "add 15 minutes," and "is this expired?" It is a poor model for "every second Tuesday," "end of month in Asia/Kolkata," or "parse DD/MM/YYYY vs MM/DD/YYYY from user input." Libraries (Luxon, date-fns + date-fns-tz, Temporal polyfills) give immutable types, explicit zones, and duration objects. Moment.js is in maintenance mode — do not start new work on it.// Platform-first: expiry check, no library
function isExpired(isoUtc, now = Date.now()) {
const t = Date.parse(isoUtc);
if (Number.isNaN(t)) throw new TypeError("Invalid ISO date");
return t <= now;
}
// Platform-first: format in a known zone
function formatInZone(isoUtc, timeZone, locale = "en-IN") {
return new Intl.DateTimeFormat(locale, {
dateStyle: "full",
timeStyle: "short",
timeZone,
}).format(new Date(isoUtc));
}
// Library territory (conceptual — Temporal / Luxon-shaped)
// ZonedDateTime.from({ year: 2026, month: 3, day: 8, hour: 2, timeZone: "America/New_York" })
// .plus({ days: 1 }) // DST-safe calendar arithmetic
// .toISO()
const nativeEnough = {
store: "ISO-8601 UTC strings or epoch ms",
display: "Intl.DateTimeFormat + IANA timeZone",
simpleMath: "setDate / getTime offsets",
};
const reachForALibrary = {
parse: "ambiguous locale date strings",
recurrence: "RRULE, business days, holidays",
zones: "convert wall time in zone A to zone B",
calendars: "Hijri, fiscal quarters, weeks that start Saturday",
};Temporal (stage 4 in the language, shipping gradually) splits instant, plain date, plain time, and zoned date-time so you cannot accidentally mix them. Until it is everywhere, a thin helper module plus Intl beats pulling 200 KB of date code for a blog timestamp. Measure: if your bugs are timezone-related and recurring, the library pays for itself; if you only format createdAt, stay native.
JSON.parse a date string back into new Date inside a recursive walker without a schema. APIs should send ISO strings; the client parses at the boundary once.Storage and persistence
2 items40localStorage, sessionStorage, and cookies
localStorage persists per origin until cleared; sessionStorage lasts for the tab; cookies are sent on matching HTTP requests and are the only one of the three the server can read automatically.https://app.example.com cannot read https://other.example.com). localStorage and sessionStorage are synchronous string maps (~5 MB typical). They never go to the network. Cookies are small (4 KB each), included on requests when Path / Domain / SameSite match, and can be HttpOnly so JavaScript cannot read them — which is what you want for session cookies.localStorage.setItem("theme", "dark");
localStorage.getItem("theme"); // "dark"
localStorage.removeItem("theme");
sessionStorage.setItem("draft", JSON.stringify({ title: "Untitled" }));
const draft = JSON.parse(sessionStorage.getItem("draft") ?? "null");
function setJSON(key, value) {
localStorage.setItem(key, JSON.stringify(value));
}
function getJSON(key, fallback = null) {
try {
const raw = localStorage.getItem(key);
return raw == null ? fallback : JSON.parse(raw);
} catch {
return fallback;
}
}
// Cookie the server can set as HttpOnly; JS-visible cookies look like:
document.cookie; // "a=1; b=2" — no HttpOnly cookies here
document.cookie = "sidebar=collapsed; Max-Age=31536000; Path=/; SameSite=Lax";setItem throws QuotaExceededError when the origin is full — wrap writes in try/catch. Storage events fire in other tabs of the same origin when localStorage changes, not in the tab that wrote. sessionStorage is copied when you duplicate a tab in some browsers, but a new tab opened via URL has empty session storage. Do not store secrets, tokens with long life, or large JSON blobs in localStorage (XSS can read it; see lesson 50).
SameSite=Lax is a sensible default for cookies the site needs on top-level navigations. Use SameSite=Strict for extra CSRF resistance; SameSite=None; Secure only for cross-site embeds over HTTPS.localStorage and read it on load. Save a form draft in sessionStorage. Confirm the draft vanishes in a new tab but the theme does not. Inspect document.cookie vs Application → Cookies in DevTools.41IndexedDB and quotas
localStorage, IndexedDB is asynchronous, can store Blobs / ArrayBuffers / structured clones, and supports indexes and transactions. You open a database with a version; onupgradeneeded is the only place to create object stores. Reads and writes happen inside transactions (readonly or readwrite). Wrapping IDB in promises (or using a small helper like idb) is standard because the raw API is event-based.function openNotesDb() {
return new Promise((resolve, reject) => {
const req = indexedDB.open("notes-app", 1);
req.onupgradeneeded = () => {
const db = req.result;
if (!db.objectStoreNames.contains("notes")) {
const store = db.createObjectStore("notes", { keyPath: "id" });
store.createIndex("byUpdated", "updatedAt");
}
};
req.onsuccess = () => resolve(req.result);
req.onerror = () => reject(req.error);
});
}
async function putNote(note) {
const db = await openNotesDb();
return new Promise((resolve, reject) => {
const tx = db.transaction("notes", "readwrite");
tx.objectStore("notes").put(note);
tx.oncomplete = () => resolve();
tx.onerror = () => reject(tx.error);
});
}
async function estimateStorage() {
if (!navigator.storage?.estimate) return null;
const { usage, quota } = await navigator.storage.estimate();
return { usage, quota, pct: usage / quota };
}
async function tryPersist() {
if (!navigator.storage?.persist) return false;
return navigator.storage.persist(); // may prompt; not guaranteed
}Quota is not a fixed 5 MB. Browsers grant a fraction of disk (often large) but may evict best-effort data when space is tight. navigator.storage.persist() asks the browser to treat the origin as persistent (user permission / engagement heuristics). Cache Storage (service workers) and IndexedDB share the same bucket. Always handle QuotaExceededError and design for "data may disappear" unless you also sync to a server.
localStorage is simpler.put three notes, query the byUpdated index. Call navigator.storage.estimate() and log usage vs quota. Optionally request persist() and read navigator.storage.persisted().Network and HTTP
3 items42fetch and AbortController
fetch returns a promise for a Response; you must check response.ok yourself. AbortController cancels the request when the user navigates away, types a new query, or a timeout fires.fetch(url) resolves on an HTTP response, including 404 and 500 — those are not network failures. A thrown error means the request did not complete (offline, CORS blocked, aborted). Read the body once (response.json(), response.text(), response.blob()). Pass signal from AbortController so fetch rejects with AbortError when you call abort(). Aborting in-flight work is how you avoid race conditions: the slow old search must not overwrite the new one.async function getJSON(url, { signal, timeoutMs = 8_000 } = {}) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), timeoutMs);
if (signal) {
signal.addEventListener("abort", () => controller.abort(), { once: true });
}
try {
const res = await fetch(url, {
signal: controller.signal,
headers: { Accept: "application/json" },
});
if (!res.ok) {
throw new Error(`HTTP ${res.status} ${res.statusText}`);
}
return await res.json();
} catch (err) {
if (err.name === "AbortError") {
throw new Error("Request cancelled or timed out", { cause: err });
}
throw err;
} finally {
clearTimeout(timer);
}
}
// Cancel previous search when the query changes
let searchAbort;
async function search(query) {
searchAbort?.abort();
searchAbort = new AbortController();
return getJSON(`/api/search?q=${encodeURIComponent(query)}`, {
signal: searchAbort.signal,
});
}Default fetch is GET with credentials: "same-origin" in browsers (cookies for same site). For POST, set method, headers, and body. keepalive: true lets a fetch outlive the page (analytics on unload) with a small body limit. Streams (res.body.getReader()) are for large downloads you process incrementally.
AbortError as a normal control-flow outcome, not a toast-worthy failure, when the user cancelled or typed again.43Retry, backoff, and FormData
FormData builds multipart/form-data bodies for files without manual MIME boundaries.fetch can fail because a load balancer was restarting. Blind for loops that immediately retry can stampede the server. Backoff waits base * 2 ** attempt milliseconds, plus random jitter so clients do not sync up. Honor Retry-After on 429 when present. Idempotent methods (GET, PUT, DELETE) are safer to retry than POST unless the server uses idempotency keys.function sleep(ms, signal) {
return new Promise((resolve, reject) => {
const id = setTimeout(resolve, ms);
signal?.addEventListener(
"abort",
() => {
clearTimeout(id);
reject(new DOMException("Aborted", "AbortError"));
},
{ once: true }
);
});
}
async function fetchWithRetry(url, options = {}, { retries = 3, baseMs = 300 } = {}) {
let lastError;
for (let attempt = 0; attempt <= retries; attempt++) {
try {
const res = await fetch(url, options);
if (res.status === 429 || res.status >= 500) {
if (attempt === retries) return res;
const retryAfter = Number(res.headers.get("Retry-After"));
const wait = Number.isFinite(retryAfter)
? retryAfter * 1000
: baseMs * 2 ** attempt + Math.random() * baseMs;
await sleep(wait, options.signal);
continue;
}
return res;
} catch (err) {
lastError = err;
if (err.name === "AbortError" || attempt === retries) throw err;
await sleep(baseMs * 2 ** attempt + Math.random() * baseMs, options.signal);
}
}
throw lastError;
}
function uploadProfile(file, fields) {
const body = new FormData();
body.append("avatar", file, file.name);
body.append("displayName", fields.displayName);
return fetch("/api/profile", { method: "POST", body });
// Do NOT set Content-Type — the browser adds the multipart boundary
}FormData also comes from <form> via new FormData(formElement). JSON is still the right default for APIs that do not need files. Mixing retries with non-idempotent POST can duplicate charges or comments — coordinate with the backend.
Content-Type: multipart/form-data yourself, you omit the boundary and the server cannot parse the body. Let fetch + FormData set the header.fetchWithRetry against a URL that returns 503 twice then 200 (use a mock or httpstat.us). Upload a file from an <input type="file"> with FormData and log res.status.44CORS
https://notes.example:443). fetch to a different origin is cross-origin. Simple requests (GET/POST with a few content types) go out; JavaScript can read the body only if Access-Control-Allow-Origin matches. Requests with custom headers, PUT/DELETE, or Content-Type: application/json trigger a preflight OPTIONS request. The server must answer with allow-origin, allow-methods, and allow-headers. credentials: "include" requires a specific origin (not *) and Access-Control-Allow-Credentials: true.// Cross-origin JSON with cookies (only works if the API allows this origin)
async function loadProfile(apiBase) {
const res = await fetch(`${apiBase}/me`, {
method: "GET",
credentials: "include",
headers: { Accept: "application/json" },
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
}
// What a cooperative API must send (server-side sketch, not browser JS)
const corsHeaders = {
"Access-Control-Allow-Origin": "https://app.example.com",
"Access-Control-Allow-Credentials": "true",
"Access-Control-Allow-Methods": "GET, POST, PUT, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type, Authorization",
"Access-Control-Max-Age": "86400",
};
// Same-origin or a proxy avoids CORS in development
// next.config rewrites: /api/* → https://backend.example.com/api/*A CORS error in the console is not a failed TCP connection — the response often arrived, but the browser hid it from JS. Postman and curl have no CORS. Fixing it means changing the API (or using a same-origin proxy), not adding a browser flag. no-cors mode gives an opaque response you cannot read — it is not a workaround for APIs.
/api to the backend so the browser sees one origin. In production, configure the real Access-Control-Allow-Origin list; never reflect arbitrary Origin headers without a allowlist.fetch a public API that sends Access-Control-Allow-Origin: * (it should work). Then fetch a URL that does not (e.g. https://example.com) and read the exact DevTools error. Sketch the preflight + response headers the second server would need.Regex in practice
2 items45Groups and lookahead
(?:...) is non-capturing. (?<name>...) is named. After exec or match, numbered groups are on the array; named groups live on match.groups. Lookahead (?=...) / (?!...) and lookbehind (?<=...) / (?<!...) succeed or fail based on what is ahead or behind, leaving the current position unchanged. That lets you say "a number not followed by px" or "password has a digit somewhere" without consuming the whole string twice.const iso = /^(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})$/;
const m = iso.exec("2026-09-08");
m.groups.year; // "2026"
const price = /(?<currency>USD|INR|EUR)\s(?<amount>\d+(?:\.\d{2})?)/;
price.exec("INR 1299.00")?.groups;
// Password: 8+ chars, at least one letter and one digit (lookaheads)
const strongEnough = /^(?=.*[A-Za-z])(?=.*\d).{8,}$/;
strongEnough.test("secret99"); // true
// Word not preceded by @ (not a mention)
const bareWord = /(?<!@)\b[A-Za-z]+\b/g;
"hi @ada and bob".match(bareWord); // ["hi", "and", "bob"]
const re = /(\w+)\s+(\w+)/;
re.exec("Ada Lovelace");
// [full, "Ada", "Lovelace", index, input, groups]g (global) + exec in a loop advances lastIndex; forgetting that causes infinite loops or skipped matches. d flag (hasIndices) adds indices for highlight ranges. Flags i, m, s change case, ^/$ line behavior, and whether . matches newlines. Prefer String.prototype.matchAll for global named groups.
DOMParser. Regex is for regular languages — HTML is not one.rgb(r, g, b) and extract the three numbers. Add a negative lookahead so rgba(...) does not match. Test "rgb(1, 2, 3)" and "rgba(1, 2, 3, 0.5)".46Safe validation
(a+)+$ on a long string of as with a failing suffix freeze the main thread. Keep patterns simple, use possessive or atomic ideas where the engine supports them, and set a length cap before running the regex. For email, check for @ and a reasonable length, then let the server and a confirmation mail decide. For numbers, Number + range checks beat a 40-character pattern.function hasReDosShape(source) {
return /(\+|\*)\{.*,.*\}/.test(source) || /(\([^)]+[+*)][^)]*){2,}/.test(source);
}
function safeTest(re, input, { maxLen = 256 } = {}) {
if (typeof input !== "string" || input.length > maxLen) return false;
return re.test(input);
}
const EMAIL_LOOSE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
function looksLikeEmail(value) {
return safeTest(EMAIL_LOOSE, value, { maxLen: 254 });
}
function parsePort(raw) {
if (typeof raw !== "string" || raw.length > 5) return null;
if (!/^\d{1,5}$/.test(raw)) return null;
const n = Number(raw);
return n >= 1 && n <= 65535 ? n : null;
}
function escapeRegExp(literal) {
return literal.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function containsWord(haystack, word) {
const re = new RegExp(`\\b${escapeRegExp(word)}\\b`, "i");
return safeTest(re, haystack, { maxLen: 10_000 });
}When users supply the pattern (new RegExp(userInput)), you are handing them a CPU bomb and an injection surface. Escape literals with escapeRegExp. Validate on the server even if the client already did — client checks are UX, not security. Prefer denylist-light, allowlist-heavy rules (/^[A-Za-z0-9_-]{1,32}$/ for a slug).
/^(a+)+$/ against "aaaaaaaaaaaaaaaaaaaa!" with console.time. Then rewrite the check as input.length <= 32 && /^a+$/.test(input) and compare. Add escapeRegExp tests for foo.bar vs fooXbar.Browser APIs and performance
2 items47IntersectionObserver and ResizeObserver
scroll and resize to layout-thrashing reads. IntersectionObserver tells you when an element enters a box; ResizeObserver tells you when its box changes.getBoundingClientRect() inside a scroll handler — forced layout every frame. IntersectionObserver delivers a list of entries when the target crosses a threshold of the viewport (or a custom root). ResizeObserver fires when the observed element's content box changes, including CSS container queries-style layouts, without listening to window.resize (which misses flex/grid sibling changes).function observeOnce(el, callback, { threshold = 0.25 } = {}) {
const io = new IntersectionObserver(
(entries, observer) => {
for (const entry of entries) {
if (!entry.isIntersecting) continue;
callback(entry);
observer.unobserve(entry.target);
}
},
{ root: null, rootMargin: "200px 0px", threshold }
);
io.observe(el);
return () => io.disconnect();
}
function onBoxChange(el, callback) {
const ro = new ResizeObserver((entries) => {
for (const entry of entries) {
const box = entry.contentBoxSize?.[0] ?? {
inlineSize: entry.contentRect.width,
blockSize: entry.contentRect.height,
};
callback({ width: box.inlineSize, height: box.blockSize, entry });
}
});
ro.observe(el);
return () => ro.disconnect();
}
const img = document.querySelector("img[data-src]");
if (img) {
observeOnce(img, () => {
img.src = img.dataset.src;
});
}Always disconnect or unobserve when the component unmounts — observers keep targets alive and leak. rootMargin grows the detection box (preload 200px before the image appears). Multiple thresholds ([0, 0.5, 1]) give progress for reading indicators. contentBoxSize is an array (multi-column); fall back to contentRect in older engines.
getBoundingClientRect() inside the ResizeObserver callback and then write styles that change size again — you can loop. Apply classes or update a store; let CSS finish the layout.48Web Workers and requestIdleCallback
requestIdleCallback schedules leftover main-thread work for idle periods — not a substitute for workers.self) with no DOM. You postMessage structured-cloneable data (or Transferables like ArrayBuffer) and listen for results. Workers cannot touch document; they can use fetch, IndexedDB (in dedicated workers), and OffscreenCanvas where supported.// worker.js
self.onmessage = (event) => {
const { id, text } = event.data;
const wordCount = text.trim() === "" ? 0 : text.trim().split(/\s+/).length;
self.postMessage({ id, wordCount });
};
// main.js
const worker = new Worker(new URL("./worker.js", import.meta.url), { type: "module" });
function countWordsOffThread(text) {
const id = crypto.randomUUID();
return new Promise((resolve, reject) => {
function onMessage(event) {
if (event.data.id !== id) return;
worker.removeEventListener("message", onMessage);
resolve(event.data.wordCount);
}
worker.addEventListener("message", onMessage);
worker.addEventListener("error", reject, { once: true });
worker.postMessage({ id, text });
});
}
function scheduleAnalytics(payload) {
const run = (deadline) => {
while (deadline.timeRemaining() > 0 && payload.length) {
const item = payload.shift();
navigator.sendBeacon?.("/analytics", JSON.stringify(item));
}
if (payload.length) requestIdleCallback(run, { timeout: 2000 });
};
if (typeof requestIdleCallback === "function") {
requestIdleCallback(run, { timeout: 2000 });
} else {
setTimeout(() => run({ timeRemaining: () => 16 }), 0);
}
}requestIdleCallback is for deferrable main-thread work (prefetch, analytics, non-critical DOM). The timeout option forces a run so work is not starved on a busy page. Safari support has lagged — always polyfill with setTimeout. Do not put input handling in idle callbacks. Prefer workers for anything that can exceed a few milliseconds of CPU.
ArrayBuffers (postMessage(buf, [buf])) or share a SharedArrayBuffer only with a clear memory model.requestIdleCallback and log deadline.timeRemaining().Security basics
2 items49XSS, sanitization, and CSP
innerHTML; sanitize or use textContent, and lock down what can execute with Content-Security-Policy.user.name as HTML and the name is <img src=x onerror=alert(1)>, the handler runs as your site. Stored XSS sits in the database; reflected XSS rides on a URL parameter; DOM XSS is entirely in client-side sinks (innerHTML, document.write, eval, new Function, href="javascript:"). The fix is to treat all external data as text unless you have a sanitizer that allows a safe tag subset (DOMPurify or the Sanitizer API). Frameworks that default to escaping (textContent, React children) close the common hole — dangerouslySetInnerHTML opens it again.function renderComment(el, userText) {
el.textContent = userText; // safe: no HTML parse
}
function escapeHtml(s) {
return s
.replaceAll("&", "&")
.replaceAll("<", "<")
.replaceAll(">", ">")
.replaceAll('"', """)
.replaceAll("'", "'");
}
function setSafeHtml(el, untrusted) {
el.innerHTML = escapeHtml(untrusted);
}
function unsafe(el, untrusted) {
el.innerHTML = untrusted; // XSS if untrusted is markup
}
const cspExample = [
"default-src 'self'",
"script-src 'self'",
"style-src 'self' 'unsafe-inline'",
"img-src 'self' data: https:",
"connect-src 'self' https://api.example.com",
"object-src 'none'",
"base-uri 'self'",
"frame-ancestors 'none'",
].join("; ");CSP is an HTTP header (or <meta>) that tells the browser which origins may supply scripts, styles, images, and connections. 'unsafe-inline' for scripts defeats much of XSS protection; prefer hashes or nonces. script-src 'self' blocks inline event handlers and surprise CDNs. CSP is defense in depth — it does not replace escaping. Also encode for the right context: HTML body, HTML attribute, JS string, and URL each need different escaping.
innerHTML, dangerouslySetInnerHTML, and eval. Each hit needs a justification and a sanitizer or a rewrite to textContent.<img src=x onerror=alert(1)> through textContent vs innerHTML on a dummy element. Draft a CSP for this notes app ('self' scripts, images from your origin). Confirm a blocked inline script in DevTools → Console.50Token storage
localStorage are stolen by any XSS. Prefer short-lived tokens in memory plus HttpOnly, Secure, SameSite cookies for the refresh/session — or a BFF that never exposes the raw token to JavaScript.localStorage is trivial to read from a script tag the attacker wrote — one XSS and the token is gone. An in-memory variable dies on refresh (you re-bootstrap via a cookie). An HttpOnly cookie cannot be read by document.cookie, so XSS cannot exfiltrate it directly; you then need CSRF defenses (SameSite, anti-CSRF tokens, custom headers). Never put long-lived refresh tokens in localStorage or log them.let accessToken = null; // memory only — gone on reload
async function bootstrapSession() {
const res = await fetch("/api/auth/refresh", {
method: "POST",
credentials: "include", // send HttpOnly refresh cookie
});
if (!res.ok) {
accessToken = null;
return null;
}
const data = await res.json();
accessToken = data.accessToken; // short-lived, e.g. 5–15 minutes
return accessToken;
}
async function apiFetch(url, options = {}) {
const headers = new Headers(options.headers);
if (accessToken) headers.set("Authorization", `Bearer ${accessToken}`);
const res = await fetch(url, { ...options, headers, credentials: "include" });
if (res.status !== 401) return res;
const next = await bootstrapSession();
if (!next) return res;
headers.set("Authorization", `Bearer ${next}`);
return fetch(url, { ...options, headers, credentials: "include" });
}
const cookieFlags = {
HttpOnly: true,
Secure: true, // HTTPS only
SameSite: "Lax",
Path: "/api/auth",
MaxAge: 60 * 60 * 24 * 7,
};The cookie must be Secure in production and scoped with Path / Domain as tightly as possible. Third-party cookies are restricted — do not design new auth on cross-site cookie sharing. For SPAs talking to a separate API, a same-origin backend-for-frontend that holds the session and proxies API calls keeps tokens off the frontend entirely. Lesson 49 is a prerequisite: cookie-based auth is only as strong as your XSS hygiene.
apiFetch against a mock that returns 401 once, then succeeds after bootstrapSession.Data Types
4 items01JavaScript is dynamically typed and weakly typed, meaning
Types are determined at runtime. Implicit type coercion can occur. JavaScript data types are divided into Primitive and Non-Primitive (Reference) types.
02Primitive Data Types
ex. Number , BigInt , String , undefined , null , boolean , symbol
- Primitive Data Types
03Non-Primitive (Reference) Types
ex. object , array , functions
- Non-Primitive (Reference) Types
// Primitive vs Reference04Copy behavior
- Copy behavior
let a = 10;
let b = a;
b = 20; // a unchanged
let obj1 = { x: 1 };
let obj2 = obj1;
obj2.x = 2; // obj1.x also changes
// typeof Operator
typeof 42; // "number"
typeof "hi"; // "string"
typeof true; // "boolean"
typeof undefined; // "undefined"
typeof null; // "object"
typeof {}; // "object"
typeof []; // "object"
typeof function () {}; // "function"
// Memory Model Summary
// | Type | Stored As | Mutable |
// | --------- | --------- | ------- |
// | Primitive | Value | No |
// | Object | Reference | Yes |
// Mutable vs Immutable
// Primitives are immutable because they represent single, fixed values
// Non-primitives (objects) are mutable because they represent collections of
// values stored by reference
// ex.
"hello".toUpperCase();
// Looks like mutation — but it’s not.
// What actually happens:
// JS creates a temporary object, calls the method, then discards it:
const upper = "hello".toUpperCase();
console.log(upper); // "HELLO"
console.log("hello"); // still "hello"
// Returns a new string
// Discards the object
// Original value unchanged.Variables
10 items01A variable is a named container that stores data in memory s
// | Keyword | Scope | Reassign | Hoisted | Use Case |
// | ------- | -------- | -------- | ------- | --------- |02Notes
var | Function | ✅ | Yes | ❌ Avoid |03Notes
let | Block | ✅ | No* | ✅ Default |04Notes
const | Block | ❌ | No* | ✅ Default |// | Declaration | Hoisted | Initialized |
// | ----------- | ------- | ----------- |05Notes
var | ✅ | undefined |06Notes
let | ✅ | ❌ | if access before initialization gives ReferenceError07Notes
const | ✅ | ❌ | if access gives ReferenceError{
var a = "sasads";
}
console.log(a); // sasads
// var is NOT block-scoped.
// var is function-scoped.
// Execution Context - > variables
// Every time JS runs code, it creates an Execution Context:
// Execution Context Contains:
// Memory (Variable Environment)
// Code (Execution Thread)
// Types:
// Global Execution Context
// Function Execution Context
// Start Program
// ↓
// Create Global Execution Context
// ↓
// Memory Creation Phase
// ↓
// Execution Phase
// ↓
// Program End
// | Keyword | Memory Phase | Access Before Init |
// | ------- | ------------ | ------------------ |08Notes
var | undefined | ✅ allowed |09Notes
let | TDZ | ❌ error |10Notes
const | TDZ | ❌ error |// JavaScript first allocates memory, then executes code line-by-line.
// *******************-**********************
// Function Execution in JavaScript
// Function execution is the process where JavaScript allocates memory for a function and
// its variables, then runs the function code when it is called.
// Concept
// JavaScript runs code in two phases:
// Memory Creation Phase – function is stored in memory
// Execution Phase – function runs when called
// Every function call creates a new execution context
// The call stack manages which function runs firstMath
2 items01JavaScript Math Operators & Math Methods
Operators;
// + Addition
// - Subtraction
// * Multiplication
// / Division
// % Remainder
// ** Exponentiation
// Addition: adds two numbers
let add = 10 + 3; // output: 13
// Subtraction: subtracts one number from another
let sub = 10 - 3; // output: 7
// Multiplication: multiplies two numbers
let mul = 10 * 3; // output: 30
// Division: divides one number by another
let div = 10 / 3; // output: 3.3333333333333335
// Remainder: returns remainder after division
let rem = 10 % 3; // output: 1
// Exponentiation: raises power
let exp = 10 ** 3; // output: 1000
// Math is a built-in JavaScript object that provides mathematical constants and functions.
// Math.pow(): returns power of a number
let power = Math.pow(2, 4); // output: 16
// Math.sqrt(): returns square root
let sqrt = Math.sqrt(16); // output: 4
// Math.floor(): rounds down
let floor = Math.floor(4.9); // output: 4
// Math.ceil(): rounds up
let ceil = Math.ceil(4.1); // output: 5
// Math.round(): rounds to nearest integer
let round = Math.round(4.5); // output: 5
// Math.random(): returns random number between 0 and 1
let random = Math.random(); // output: random value (0–1)
// Math.min(): returns smallest value
let min = Math.min(1, 5, 3); // output: 1
// Math.max(): returns largest value
let max = Math.max(1, 5, 3); // output: 5
// Math.abs(): returns absolute value
let abs = Math.abs(-20); // output: 20
// Infinity: represents infinite value
let inf = 1 / 0; // output: Infinity
// NaN: represents not-a-number
let nan = Math.sqrt(-1); // output: NaN
// other
// max - min + 1 = total possible numbers
// Math.floor(Math.random() * (max - min + 1)) + min
const a = Math.floor(Math.random() * (20 - 10 + 1)) + 10;
console.log(a);
// other
// ?? (Nullish Coalescing) Operator in JavaScript
// Definition
// The ?? operator returns the right-hand value only when the left-hand value is null or undefined.
let score = 0;
let result = score ?? 10; // output: 0
score || 10; // output: 10
score ?? 10; // output: 0
// Compound Operators in JavaScript
// Compound operators combine a mathematical operation with an assignment (=) in a shorter form.02Operator · Long Form · Short Form
| Operator | Long Form | Short Form |
|---|---|---|
+= | x = x + y | x += y |
-= | x = x - y | x -= y |
*= | x = x * y | x *= y |
/= | x = x / y | x /= y |
%= | x = x % y | x %= y |
**= | x = x ** y | x **= y |
Loops
9 items01JavaScript Loops – All Types
// A loop is used to run the same code repeatedly until a condition is met
// --------------------------------02for loop
- for loop
for (let i = 1; i <= 5; i++) {
console.log(i); // output: 1 2 3 4 5
}
// --------------------------------03while loop
- while loop
let w = 1;
while (w <= 5) {
console.log(w); // output: 1 2 3 4 5
w++;
}
// --------------------------------04do...while loop
- do...while loop
let d = 1;
do {
console.log(d); // output: 1 2 3 4 5
d++;
} while (d <= 5);
// --------------------------------05for...in loop
- for...in loop
const obj = { name: "Alice", age: 25 };
for (let key in obj) {
console.log(key, obj[key]);
// output: name Alice
// age 25
}
// --------------------------------06for...of loop
- for...of loop
const arr = [10, 20, 30];
for (let value of arr) {
console.log(value); // output: 10 20 30
}
// --------------------------------07forEach loop (Array method)
- forEach loop (Array method)
arr.forEach((item) => {
console.log(item); // output: 10 20 30
});
// --------------------------------08break statement
- break statement
for (let i = 1; i <= 5; i++) {
if (i === 3) break;
console.log(i); // output: 1 2
}
// --------------------------------09continue statement
- continue statement
for (let i = 1; i <= 5; i++) {
if (i === 3) continue;
console.log(i); // output: 1 2 4 5
}
// ===============================
// Summary (In Comments)
// ===============================
// for -> known number of iterations
// while -> condition-based loop
// do...while-> runs at least once
// for...in -> object keys
// for...of -> iterable values
// forEach -> array iteration method
// break -> exit loop
// continue -> skip iterationHoisting
55 items01Hoisting is JavaScript’s default behavior of moving declarat
02Declaration Type · Hoisted? · Initialized? · Can Use Before
| Declaration Type | Hoisted? | Initialized? | Can Use Before Decl? |
|---|---|---|---|
var | ✅ Yes | ✅ undefined | ⚠️ Yes (undefined) |
let | ✅ Yes | ❌ No | ❌ No (TDZ) |
const | ✅ Yes | ❌ No | ❌ No (TDZ) |
| Function Decl. | ✅ Yes | ✅ Yes | ✅ Yes |
| Function Expr. | Depends | Depends | ❌ Usually No |
| Arrow Function | Depends | Depends | ❌ No |
| Class | ✅ Yes | ❌ No | ❌ No (TDZ) |
03Variable Hoisting
- Variable Hoisting
console.log(a); // undefined
var a = 10;
// How JavaScript sees it internally:
var a;
console.log(a);
a = 10;
// No error, but value is undefined
// let and const
// Hoisted, but not initialized
// Exist in the Temporal Dead Zone (TDZ) until declaration is reached
console.log(b); // ❌ ReferenceError
let b = 20;
console.log(c); // ❌ ReferenceError
const c = 30;04TDZ = time between entering scope and actual declaration
// ------------------------------------------------------------------------------------------05Function Hoisting
- Function Hoisting
// Function Declarations - Fully hoisted (both name and body)
sayHello(); // works
function sayHello() {
console.log("Hello!");
}
// Function Expressions -Hoisting depends on how they are declared
// With var
sayHi(); // ❌ TypeError: sayHi is not a function
var sayHi = function () {
console.log("Hi");
};06Why?
var sayHi; // hoisted as undefined sayHi(); // undefined() sayHi = function() {};
With let / const sayHey(); // ❌ ReferenceError
const sayHey = function () { console.log("Hey"); };
07Arrow Functions - Arrow functions behave like function expressions
hello(); // ReferenceError
const hello = () => {
console.log("Hello");
};08Class Hoisting - Classes are hoisted but not initialized (like let / const)
- Class Hoisting - Classes are hoisted but not initialized (like let / const).
const user = new User(); // ReferenceError
class User {
constructor(name) {
this.name = name;
}
}09ARROW FUNCTION vs FUNCTION DECLARATION All examples and defi
10FUNCTION DECLARATION
- FUNCTION DECLARATION
- Fully hoisted (can be used before definition)
- Has its own
this - Has its own
argumentsobject - Can be used as a constructor (with
new)
11Example
sayHello2(); // ✅ Works because function declarations are hoisted
function sayHello2() {
console.log("Hello from function declaration");
}12ARROW FUNCTION
- ARROW FUNCTION
- NOT hoisted like function declarations
- Does NOT have its own
this - Does NOT have
arguments - Cannot be used as a constructor
- Shorter syntax
13greet(); // ❌ ReferenceError (cannot access before initialization)
const greet = () => {
console.log("Hello from arrow function");
};
greet(); // ✅ Works after declaration14THIS BEHAVIOR (MOST IMPORTANT DIFFERENCE)
- THIS BEHAVIOR (MOST IMPORTANT DIFFERENCE)
15Function Declaration → this is dynamic
this is dynamicconst user1 = {
name: "Alice",
greet: function () {
console.log("Function this:", this.name);
},
};
user1.greet(); // ✅ Alice
// Arrow Function → `this` is lexical (inherits from parent scope)
const user2 = {
name: "Bob",
greet: () => {
console.log("Arrow this:", this.name);
},
};
user2.greet(); // ❌ undefined (arrow has no own `this`)16THIS INSIDE CALLBACKS
- THIS INSIDE CALLBACKS
17Example
function TimerWithFunction() {
this.count = 0;
setInterval(function () {18❌ this is not TimerWithFunction
this is not TimerWithFunction console.log(this.count); // undefined}, 1000);
}
function TimerWithArrow() {
this.count = 0;
setInterval(() => {19✅ arrow inherits this from TimerWithArrow
this from TimerWithArrowthis.count++;
console.log("Arrow timer:", this.count);
}, 1000);
}
// Uncomment to test
// new TimerWithArrow();20ARGUMENTS OBJECT
- ARGUMENTS OBJECT
21Example
function normalFunction() {
console.log("Function arguments:", arguments);
}
normalFunction(1, 2, 3);22Arrow functions do NOT have arguments
argumentsconst arrowFunction = () => {23console.log(arguments); // ❌ ReferenceError
};
// Correct way with arrow function
const arrowWithRest = (...args) => {
console.log("Arrow rest args:", args);
};
arrowWithRest(1, 2, 3);24WHEN TO USE WHAT (SUMMARY)
Use FUNCTION DECLARATION when:
- You need hoisting
- You need dynamic
this - You need constructors or prototypes
Use ARROW FUNCTION when:
- Writing callbacks
- Using array methods (map, filter, reduce)
- You want lexical
this - You want cleaner, shorter syntax
25Function *--------------------------------------------------
26FUNCTION DECLARATION
- FUNCTION DECLARATION
27function add(a, b) {
28FUNCTION EXPRESSION
- FUNCTION EXPRESSION
29const add = function (a, b) {
30ARROW FUNCTION
- ARROW FUNCTION
31const add = (a, b) => a + b;
32ANONYMOUS FUNCTION
- ANONYMOUS FUNCTION
33setTimeout(function () {
34NAMED FUNCTION EXPRESSION
- NAMED FUNCTION EXPRESSION
35const factorial = function fact(n) {
1 : n * fact(n - 1); };
36IMMEDIATELY INVOKED FUNCTION EXPRESSION (IIFE)
- IMMEDIATELY INVOKED FUNCTION EXPRESSION (IIFE)
37(function () {
38GENERATOR FUNCTION
- GENERATOR FUNCTION
39function* generatorExample() {
40ASYNC FUNCTION
- ASYNC FUNCTION
41async function fetchData() {
42ASYNC ARROW FUNCTION
- ASYNC ARROW FUNCTION
43const fetchData = async () => {
44CALLBACK FUNCTION
- CALLBACK FUNCTION
45function callbackExample(cb) {
46A function that takes a function as a argument and returns a
- HIGHER-ORDER FUNCTION
47function higherOrder(fn) {
48CONSTRUCTOR FUNCTION
- CONSTRUCTOR FUNCTION
49function Person(name) {
50RECURSIVE FUNCTION
- RECURSIVE FUNCTION
51function factorial(n) {
1 : n * factorial(n - 1); }
52METHOD (OBJECT FUNCTION)
- METHOD (OBJECT FUNCTION)
53const obj = {
54DEFAULT PARAMETER FUNCTION
- DEFAULT PARAMETER FUNCTION
55function greet(name = "Guest") {
Code Execution
16 items01JAVASCRIPT RUNTIME DEMO
Concepts covered:
- Call Stack
- Synchronous code
- Promises (Microtask Queue)
- setTimeout (Macrotask / Callback Queue)
- Event Loop
02Example
console.log("1. Script start");03SYNC CODE (CALL STACK) Runs immediately, line by line
04Example
function syncFunction() {
console.log("2. Inside sync function");
}
syncFunction();05PROMISE (MICROTASK QUEUE) Microtasks run AFTER sync code but
06Example
Promise.resolve().then(() => {
console.log("4. Promise resolved (microtask)");
});07SETTIMEOUT (MACROTASK QUEUE) Runs AFTER microtasks
08Example
setTimeout(() => {
console.log("6. setTimeout callback (macrotask)");
}, 0);09COMPLEX NESTED EXAMPLE
10Example
setTimeout(() => {
console.log("7. setTimeout start");
Promise.resolve().then(() => {
console.log("8. Promise inside setTimeout");
});
console.log("9. setTimeout end");
}, 0);11MORE PROMISES
12Example
Promise.resolve().then(() => {
console.log("5. Second promise");
});13FINAL SYNC CODE
14Example
console.log("3. Script end");15EXPECTED OUTPUT ORDER
- Script start
- Inside sync function
- Script end
- promise
- Promise resolved (microtask)
- setTimeout callback (macrotask)
- setTimeout start
- setTimeout end
- Promise inside setTimeout
16RUNTIME EXPLANATION (MENTAL MODEL)
- Execute all SYNC code (Call Stack)
- Execute all MICROTASKS (Promises)
- Execute ONE MACROTASK (setTimeout)
- After each macrotask, clear microtasks again
- Repeat (Event Loop)
BOM
1 item01Browser Object Model (BOM)
// location → URL related info & navigation
window.location.href; // current URL
window.location.reload(); // reload page
window.location.assign(url); // navigate to new page
window.location.replace(url); // navigate without back option
// history → browser navigation
window.history.back(); // go to previous page
window.history.forward(); // go to next page
window.history.go(-1); // move by steps
// viewport size (visible browser area)
window.innerHeight;
window.innerWidth;
// open & close windows (limited by browsers)
window.open("https://example.com", "_blank");
window.close();
// resize window (mostly blocked in modern browsers)
window.resizeBy(100, 100);
window.resizeTo(800, 600);
// move window position (often blocked)
window.moveBy(50, 50);
window.moveTo(100, 100);
// scrolling the page
window.scrollBy(0, 100); // relative scroll
window.scrollTo(0, 0); // absolute scroll
window.scroll({ top: 0 }); // modern syntax
// print current page
window.print();
// document → entry point to DOM (HTML)
document.title;
document.getElementById("id");
// browser dialogs
alert("Hello");
confirm("Are you sure?");
prompt("Enter your name");DOM
8 items01DOM stands for Document Object Model
It's a programming interface provided by the browser that allows JavaScript to interact with and manipulate HTML and XML documents.
// In simple terms:
// The browser converts your HTML document into a tree-like structure (nodes and objects).
// JavaScript can use the DOM to change content, add/remove elements, style elements, or respond to events.
// <!DOCTYPE html>
// <html>
// <body>
// <h1 id="heading">Hello DOM!</h1>
// <button onclick="changeText()">Click Me</button>
// <script>
// function changeText() {
// const heading = document.getElementById("heading");
// heading.textContent = "You clicked the button!";
// }
// </script>
// </body>
// </html>
// DOM Selection Methods02document.getElementById()
- document.getElementById()
document.getElementById("idName");
// Returns:
// A single Element object, or null if not found.
const title = document.getElementById("main-title");03document.getElementsByClassName()
- document.getElementsByClassName()
document.getElementsByClassName("className");
// Returns:
// An HTMLCollection (live, array-like list of elements).
const cards = document.getElementsByClassName("card");04document.getElementsByTagName()
- document.getElementsByTagName()
document.getElementsByTagName("tagName");
// Returns:
// An HTMLCollection.
const paragraphs = document.getElementsByTagName("p");05document.querySelector()
- document.querySelector()
// Returns:
// A single Element object, or null.
const firstCard = document.querySelector(".card");
const main = document.querySelector("#main");06document.querySelectorAll()
- document.querySelectorAll()
// document.querySelectorAll("selector")
// Returns:
// A NodeList (static, array-like list of elements).
const allCards = document.querySelectorAll(".card");07Document Object Model
// The DOM is a tree-like JavaScript representation of your HTML created by the browser.08<body> <h1>Hello</h1> <p>World</p> </body>
Document └── html └── body ├── h1 │ └── "Hello" └── p └── "World"
DOM vs Virtual DOM
The DOM is a browser-created tree representation of HTML. Updating the real DOM is slow because it triggers layout and paint operations. React uses a Virtual DOM, which is a lightweight JavaScript representation of the UI, compares changes using diffing, and updates only the necessary parts of the real DOM for better performance.
Reflow vs Repaint
Reflow is when the browser recalculates layout and geometry of elements.
Repaint is when the browser redraws pixels without recalculating layout.
Difference Reflow is more expensive than repaint because it affects layout.
*
Reflow recalculates element size and position, while repaint only redraws visual changes. Reflow always triggers repaint, but repaint doesn’t trigger reflow. That’s why minimizing reflows is critical for performance.
Events
11 items01Event flow
Most handlers run on the bubble. addEventListener(type, fn, true) or { capture: true } listens on the way down. Click the child to see the order.
- Event flow
const outer = document.querySelector("#outer");
const inner = document.querySelector("#inner");
outer.addEventListener("click", () => console.log("outer bubble"));
outer.addEventListener("click", () => console.log("outer capture"), true);
inner.addEventListener("click", () => console.log("inner target"));
// typical log: outer capture → inner target → outer bubble02addEventListener options
capture, once, passive, signal (AbortController). Default is bubble + not once.
- addEventListener options
el.addEventListener("click", handler, { capture: false, once: false, passive: false });
el.addEventListener("click", handler, false); // same as capture: false
el.addEventListener("click", handler, true); // capture phase03Event delegation
Works for elements added later. Prefer closest() so clicks on inner nodes (span inside a button) still match. Check contains() if needed.
- Event delegation
list.addEventListener("click", (e) => {
const btn = e.target.closest("button[data-id]");
if (!btn || !list.contains(btn)) return;
console.log("clicked", btn.dataset.id);
});04preventDefault
Does not stop the event from traveling to other listeners. Returns false from an on* property is a legacy way to do both preventDefault and stopPropagation — avoid it.
- preventDefault
form.addEventListener("submit", (e) => {
e.preventDefault();
console.log("submit handled in JS");
});
link.addEventListener("click", (e) => {
if (!e.target.href.startsWith("https")) e.preventDefault();
});05stopPropagation vs stopImmediatePropagation
Other listeners on the SAME node still run. stopImmediatePropagation: also skips remaining listeners on this node. Does not imply preventDefault — call both if you need both.
- stopPropagation vs stopImmediatePropagation
child.addEventListener("click", (e) => {
e.stopPropagation();
console.log("child — parent will not see this click");
});
child.addEventListener("click", (e) => {
e.stopImmediatePropagation();
console.log("first only");
});
child.addEventListener("click", () => console.log("never — immediate stopped"));06once
Same as wrapping the handler and calling removeEventListener yourself. Useful for first-interaction, one-shot popovers, or init-on-click.
- once
button.addEventListener("click", () => console.log("only once"), { once: true });07passive
The browser can scroll/touch immediately without waiting for JS. Use on wheel, touch, and touchmove. Calling preventDefault inside a passive listener is ignored (and warns in DevTools). Default is false except some browser touch defaults.
- passive
window.addEventListener("touchstart", onTouch, { passive: true });
window.addEventListener(
"wheel",
(e) => {
// e.preventDefault(); // ignored if passive: true
},
{ passive: true },
);08Custom events
Set bubbles/cancelable or it stays on the target only. composed: true crosses shadow DOM. dispatchEvent is synchronous — listeners run before the next line.
- Custom events
const ping = new CustomEvent("ping", {
detail: { from: "child" },
bubbles: true,
cancelable: true,
composed: true,
});
parent.addEventListener("ping", (e) => console.log(e.detail.from));
child.dispatchEvent(ping);
document.dispatchEvent(new Event("ready")); // no detail — use Event or CustomEvent09removeEventListener pitfalls
Anonymous functions, .bind(), and wrappers are new functions — they never match. Options besides capture (once, passive) are ignored when removing. AbortController.abort() removes everything subscribed with that signal.
- removeEventListener pitfalls
function onSave() {}
el.addEventListener("click", onSave);
el.removeEventListener("click", onSave); // ok
el.addEventListener("click", () => {});
el.removeEventListener("click", () => {}); // no-op — different functions
const bound = onSave.bind(obj);
el.addEventListener("click", bound);
el.removeEventListener("click", onSave); // no-op
el.removeEventListener("click", bound); // ok
el.addEventListener("click", onSave, true);
el.removeEventListener("click", onSave); // no-op — capture mismatch
el.removeEventListener("click", onSave, true); // ok
const ac = new AbortController();
el.addEventListener("click", onSave, { signal: ac.signal });
ac.abort(); // removes it10Event object essentials
Mouse: clientX/Y, button. Keyboard: key, code, repeat. Do not confuse target with currentTarget during delegation.
- Event object essentials
el.addEventListener("click", (e) => {
e.target; // what was clicked
e.currentTarget; // always el for this listener
e.eventPhase;
});
input.addEventListener("keydown", (e) => {
if (e.key === "Enter") e.preventDefault();
});11Common listener types
- Common listener types
form.addEventListener("input", (e) => console.log(e.target.value)); // live
form.addEventListener("change", (e) => console.log(e.target.value)); // committed
el.addEventListener("focusin", (e) => e.target.classList.add("on"));Dates
40 items01Constructing a Date
The object stores UTC internally; console output uses the local timezone. Calling it as a function (Date()) returns a string, not a Date.
- Constructing a Date
const now = new Date();
console.log(now instanceof Date);
console.log(typeof Date());
console.log(now.getTime());02From Unix milliseconds
Negative values are instants before the epoch. Passing a single number is never "year" — use the multi-argument form for that.
- From Unix milliseconds
const epoch = new Date(0);
const later = new Date(1_774_310_400_000);
console.log(epoch.toISOString());
console.log(later.toISOString());03Component constructor is local
Omitted day defaults to 1; omitted time parts default to 0. Two-digit years are treated as 1900+year (99 => 1999), so prefer four digits.
- Component constructor is local
const localNoon = new Date(2026, 2, 15, 12, 0, 0);
console.log(localNoon.toString());
console.log(new Date(99, 0, 1).getFullYear());04Date.UTC and the Date wrapper
Wrap it with new Date(...) to get a Date for that instant. Component order matches the local constructor, including 0-indexed months.
- Date.UTC and the Date wrapper
const utcMs = Date.UTC(2026, 2, 15, 12, 0, 0);
const utcNoon = new Date(utcMs);
console.log(utcMs);
console.log(utcNoon.toISOString());05Parsing date strings
Only ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) is specified by the language. Other formats such as "March 15, 2026" are implementation-defined — avoid them.
- Parsing date strings
const iso = new Date("2026-03-15T12:00:00.000Z");
console.log(iso.toISOString());
console.log(Date.parse("2026-03-15T12:00:00.000Z"));06Date.parse pitfalls
Slash dates, month names, and missing timezones differ across engines. Prefer an explicit ISO string with Z, or build from numeric components.
- Date.parse pitfalls
console.log(Number.isNaN(Date.parse("not a date")));
console.log(Number.isFinite(Date.parse("2026-03-15T00:00:00Z")));
const risky = Date.parse("03/15/2026");
console.log(Number.isNaN(risky) ? "unparseable here" : new Date(risky).toISOString());07ISO date-only strings are UTC
In timezones west of UTC that is the previous local calendar day. This is the most common "off-by-one-day" bug when hydrating dates from APIs.
- ISO date-only strings are UTC
const dateOnly = new Date("2026-03-15");
console.log(dateOnly.toISOString());
console.log(dateOnly.getUTCDate());
console.log(dateOnly.getDate());08ISO datetime without Z is local
The same clock reading therefore maps to different instants per machine TZ. Always include Z or an offset when the instant must be unambiguous.
- ISO datetime without Z is local
const noZone = new Date("2026-03-15T00:00:00");
const withZ = new Date("2026-03-15T00:00:00Z");
console.log(noZone.getTime() === withZ.getTime());
console.log(noZone.toISOString());
console.log(withZ.toISOString());09Zero-indexed months
Days of month are 1–31. getDay() / getUTCDay() are also 0-indexed, but from Sunday (0) to Saturday (6). Mixing these up is the second most common Date bug after timezone parsing.
- Zero-indexed months
const march = new Date(2026, 2, 15);
console.log(march.getMonth());
console.log(march.getDate());
console.log(march.getDay());
console.log(march.getFullYear());10Invalid Dates
Its primitive value is NaN; Number(invalid) is NaN; String(invalid) is "Invalid Date". Most getters return NaN; toISOString() throws RangeError.
- Invalid Dates
const invalid = new Date("not a date");
console.log(String(invalid));
console.log(invalid.getTime());
console.log(Number.isNaN(invalid.getFullYear()));11Detecting invalid Dates
Number.isNaN(date) is always false because date is an object. Guard before formatting, comparing, or sending a Date over the wire.
- Detecting invalid Dates
function isValidDate(value) {
return value instanceof Date && !Number.isNaN(value.getTime());
}
console.log(isValidDate(new Date("2026-03-15T12:00:00Z")));
console.log(isValidDate(new Date("nope")));
console.log(isValidDate("2026-03-15"));12Local getters
getYear() is deprecated (years since 1900) — always use getFullYear().
- Local getters
const local = new Date("2026-03-15T18:30:45.250Z");
console.log(local.getFullYear(), local.getMonth(), local.getDate());
console.log(local.getHours(), local.getMinutes(), local.getSeconds(), local.getMilliseconds());
console.log(local.getDay());13UTC getters
Use these when you stored a "date" as UTC midnight and must not shift the day. Pair UTC getters with UTC setters to stay on one calendar.
- UTC getters
const instant = new Date("2026-03-15T18:30:45.250Z");
console.log(instant.getUTCFullYear(), instant.getUTCMonth(), instant.getUTCDate());
console.log(instant.getUTCHours(), instant.getUTCMinutes(), instant.getUTCSeconds());
console.log(instant.getUTCDay());14Local setters and overflow
mutate the Date in place. Out-of-range values overflow: setMonth(13) becomes February next year; setDate(0) is the last day of the previous month. They return the new getTime() value.
- Local setters and overflow
const overflow = new Date(2026, 0, 31);
overflow.setMonth(1);
console.log(overflow.toDateString());
const endOfJan = new Date(2026, 1, 1);
endOfJan.setDate(0);
console.log(endOfJan.toDateString());15UTC setters
Overflow rules are the same as the local setters. Prefer UTC setters when the Date represents a civil date stored at UTC midnight.
- UTC setters
const utcSet = new Date(Date.UTC(2026, 2, 15, 12, 0, 0));
utcSet.setUTCDate(utcSet.getUTCDate() + 1);
utcSet.setUTCHours(0, 0, 0, 0);
console.log(utcSet.toISOString());16getTime, valueOf, and Date.now
Date.now() is equivalent to Date.now = () => new Date().getTime() without allocating a Date. Use Date.now() for timestamps; use a Date object only when you need calendar fields.
- getTime, valueOf, and Date.now
const stamp = new Date("2026-03-15T00:00:00.000Z");
console.log(stamp.getTime() === stamp.valueOf());
console.log(stamp.getTime() === +stamp);
console.log(typeof Date.now() === "number");17Unix timestamps: seconds vs milliseconds
APIs (JWT exp, many databases) send seconds — multiply by 1000 before new Date. Divide getTime() by 1000 and floor when you need a Unix seconds integer.
- Unix timestamps: seconds vs milliseconds
const unixSeconds = 1773532800;
const fromUnix = new Date(unixSeconds * 1000);
console.log(fromUnix.toISOString());
console.log(Math.floor(fromUnix.getTime() / 1000) === unixSeconds);18toISOString
It is the right default for logs, JSON, and API payloads. Invalid Date causes a RangeError — validate first.
- toISOString
const isoSource = new Date("2026-03-15T12:00:00.000Z");
console.log(isoSource.toISOString());
try {
new Date("bad").toISOString();
} catch (err) {
console.log(err.name);
}19toJSON for APIs
Nested dates therefore survive a round-trip as ISO strings, not Date objects. After JSON.parse you must new Date(string) yourself.
- toJSON for APIs
const payload = { createdAt: new Date("2026-03-15T12:00:00.000Z") };
const json = JSON.stringify(payload);
const revived = JSON.parse(json);
console.log(json);
console.log(typeof revived.createdAt);
console.log(new Date(revived.createdAt).toISOString());20Locale and UTC string methods
toUTCString() is an RFC 7231-style UTC string (HTTP Date). toGMTString is an alias. These are fine for debugging; do not parse them back with new Date in production.
- Locale and UTC string methods
const shown = new Date("2026-03-15T12:00:00.000Z");
console.log(shown.toDateString());
console.log(shown.toTimeString());
console.log(shown.toUTCString());21Comparing Dates
== and === compare object identity, so two equal instants are not ===. Prefer dateA.getTime() === dateB.getTime() for equality.
- Comparing Dates
const a = new Date("2026-03-15T12:00:00Z");
const b = new Date("2026-03-15T12:00:00Z");
console.log(a === b);
console.log(a.getTime() === b.getTime());
console.log(a < new Date("2026-03-16T00:00:00Z"));22Sorting Dates
Mixing Date objects and ISO strings works if you coerce with +new Date(...) or Date.parse. Invalid Dates sort as NaN and produce an unstable order — filter them first.
- Sorting Dates
const dates = [
new Date("2026-12-01T00:00:00Z"),
new Date("2026-01-01T00:00:00Z"),
new Date("2026-06-15T00:00:00Z"),
];
dates.sort((left, right) => left.getTime() - right.getTime());
console.log(dates.map((d) => d.toISOString().slice(0, 10)));23Dates are mutable — clone first
Clone with new Date(original) or new Date(original.getTime()). structuredClone(date) also works and keeps a real Date.
- Dates are mutable — clone first
const original = new Date("2026-03-15T12:00:00Z");
const clone = new Date(original.getTime());
clone.setUTCDate(20);
console.log(original.toISOString());
console.log(clone.toISOString());24Adding and subtracting milliseconds
Adding 24 hours of milliseconds is "add 24 hours", not "add one calendar day". Across DST that distinction matters — see the DST cards.
- Adding and subtracting milliseconds
const start = new Date("2026-03-15T12:00:00Z");
const plusHour = new Date(start.getTime() + 60 * 60 * 1000);
const minusDayMs = new Date(start.getTime() - 24 * 60 * 60 * 1000);
console.log(plusHour.toISOString());
console.log(minusDayMs.toISOString());25Calendar-day arithmetic
Use setUTCDate(getUTCDate() + n) when the Date is a UTC civil date. Always clone first so the source instant stays put.
- Calendar-day arithmetic
function addLocalDays(date, days) {
const next = new Date(date.getTime());
next.setDate(next.getDate() + days);
return next;
}
console.log(addLocalDays(new Date(2026, 2, 15), 20).toDateString());
console.log(addLocalDays(new Date(2026, 0, 31), 1).toDateString());26Diff in milliseconds
Positive means the right operand is earlier when you write later - earlier. Math.abs if you only care about duration.
- Diff in milliseconds
const earlier = new Date("2026-03-15T12:00:00Z");
const laterOn = new Date("2026-03-15T15:30:00Z");
const diffMs = laterOn - earlier;
console.log(diffMs);
console.log(diffMs / 1000 / 60);27Diff in days, hours, minutes
This counts elapsed 24-hour periods, not "calendar midnights crossed". For calendar-day difference, compare UTC (or local) Y/M/D fields instead.
- Diff in days, hours, minutes
function elapsedParts(from, to) {
let ms = to.getTime() - from.getTime();
const sign = ms < 0 ? -1 : 1;
ms = Math.abs(ms);
const days = Math.floor(ms / 86_400_000);
const hours = Math.floor((ms % 86_400_000) / 3_600_000);
const minutes = Math.floor((ms % 3_600_000) / 60_000);
return { sign, days, hours, minutes };
}
console.log(elapsedParts(new Date("2026-03-15T00:00:00Z"), new Date("2026-03-17T05:10:00Z")));28Start and end of a local day
These are local-civil, so the UTC ISO string will shift with the host offset. For a UTC day, use setUTCHours instead.
- Start and end of a local day
const day = new Date(2026, 2, 15, 14, 45);
const startOfDay = new Date(day);
startOfDay.setHours(0, 0, 0, 0);
const endOfDay = new Date(day);
endOfDay.setHours(23, 59, 59, 999);
console.log(startOfDay.toString());
console.log(endOfDay.toString());
console.log(endOfDay.getTime() - startOfDay.getTime());29Leap years
Date overflow gives a cheap check: Feb 29 exists iff new Date(y, 1, 29).getMonth() === 1. 1900 is not a leap year; 2000 is.
- Leap years
function isLeapYear(year) {
return new Date(year, 1, 29).getMonth() === 1;
}
console.log(isLeapYear(2024), isLeapYear(2026));
console.log(isLeapYear(1900), isLeapYear(2000));
console.log(new Date(2024, 1, 29).toDateString());30Formatting without libraries
slice on toISOString() is a shortcut only when you want the UTC calendar date. Do not use toISOString().slice(0, 10) for a local "today" — it can be yesterday/tomorrow.
- Formatting without libraries
function formatYmdUTC(date) {
const y = date.getUTCFullYear();
const m = String(date.getUTCMonth() + 1).padStart(2, "0");
const d = String(date.getUTCDate()).padStart(2, "0");
return `${y}-${m}-${d}`;
}
function formatYmdLocal(date) {
const y = date.getFullYear();
const m = String(date.getMonth() + 1).padStart(2, "0");
const d = String(date.getDate()).padStart(2, "0");
return `${y}-${m}-${d}`;
}
const fmt = new Date("2026-03-15T02:00:00Z");
console.log(formatYmdUTC(fmt), fmt.toISOString().slice(0, 10));
console.log(formatYmdLocal(fmt));31Intl.DateTimeFormat
Default options are locale-sensitive; pass dateStyle/timeStyle or field options. format() returns a string; reuse one formatter when rendering lists.
- Intl.DateTimeFormat
const when = new Date("2026-03-15T15:30:00Z");
const us = new Intl.DateTimeFormat("en-US", { dateStyle: "medium", timeStyle: "short" });
const de = new Intl.DateTimeFormat("de-DE", { dateStyle: "medium", timeStyle: "short" });
console.log(us.format(when));
console.log(de.format(when));32Formatting in a specific timezone
This does not convert or mutate the Date; it only changes the printed fields. Invalid zone names throw RangeError at formatter construction.
- Formatting in a specific timezone
const meeting = new Date("2026-03-15T18:00:00Z");
const opts = { dateStyle: "full", timeStyle: "long", timeZone: "America/New_York" };
console.log(new Intl.DateTimeFormat("en-US", opts).format(meeting));
console.log(new Intl.DateTimeFormat("en-US", { ...opts, timeZone: "Asia/Kolkata" }).format(meeting));33formatToParts
Types include year, month, day, weekday, hour, minute, dayPeriod, timeZoneName, literal. Prefer this over regex-splitting format() output.
- formatToParts
const parts = new Intl.DateTimeFormat("en-GB", {
weekday: "short",
year: "numeric",
month: "short",
day: "2-digit",
timeZone: "UTC",
}).formatToParts(new Date("2026-03-15T00:00:00Z"));
const map = Object.fromEntries(parts.filter((p) => p.type !== "literal").map((p) => [p.type, p.value]));
console.log(map);
console.log(parts.map((p) => p.type).join(","));34Intl.RelativeTimeFormat
You supply the number and unit ("day", "hour", "month", ...); it does not diff Dates for you. numeric: "auto" yields "yesterday" / "tomorrow"; "always" yields "in 1 day".
- Intl.RelativeTimeFormat
const rtf = new Intl.RelativeTimeFormat("en", { numeric: "auto" });
console.log(rtf.format(-1, "day"));
console.log(rtf.format(3, "hour"));
console.log(new Intl.RelativeTimeFormat("en", { numeric: "always" }).format(1, "day"));35getTimezoneOffset
UTC+05:30 therefore returns -330. The sign is the opposite of the zone label. The value can change for the same Date object across DST if you mutate it.
- getTimezoneOffset
const offsetSample = new Date("2026-01-15T12:00:00Z");
const minutes = offsetSample.getTimezoneOffset();
console.log(minutes);
console.log(-minutes / 60);36DST spring-forward traps
Engines typically land on the post-gap time; do not assume 02:30 is valid. Construct civil times in a named zone via Temporal or a library, not new Date(y, m, d, 2).
- DST spring-forward traps
const ny = new Intl.DateTimeFormat("en-US", {
timeZone: "America/New_York",
timeStyle: "long",
dateStyle: "medium",
});
console.log(ny.format(new Date("2026-03-08T06:30:00Z")));
console.log(ny.format(new Date("2026-03-08T07:30:00Z")));37DST and the 24-hour day myth
Adding 86_400_000 ms can miss a local date or land at the wrong clock time. Prefer setDate(+1) for "tomorrow" and Intl or Temporal for zone-aware clocks.
- DST and the 24-hour day myth
const beforeSpring = new Date("2026-03-07T12:00:00Z");
const plus24h = new Date(beforeSpring.getTime() + 86_400_000);
const plusCalDay = new Date(beforeSpring);
plusCalDay.setUTCDate(plusCalDay.getUTCDate() + 1);
console.log(plus24h.toISOString());
console.log(plusCalDay.toISOString());
console.log(plus24h.getTime() === plusCalDay.getTime());38Temporal Instant and Now
Temporal.Now.instant() is "now"; Instant.from() parses a required-offset ISO string. Date.prototype.toTemporalInstant() bridges legacy Date when Temporal exists.
- Temporal Instant and Now
if (typeof Temporal === "undefined") {
console.log("Temporal is not available in this engine");
} else {
const instant = Temporal.Instant.from("2026-03-15T12:00:00Z");
console.log(instant.epochMilliseconds);
console.log(Temporal.Now.instant().toString());
}39Temporal PlainDate and ZonedDateTime
ZonedDateTime is an instant plus an IANA zone, so DST math is explicit. This is the model Date tried to be with one mutable object.
- Temporal PlainDate and ZonedDateTime
if (typeof Temporal === "undefined") {
console.log("Temporal is not available in this engine");
} else {
const plain = Temporal.PlainDate.from("2026-03-15");
const zoned = Temporal.ZonedDateTime.from("2026-03-15T09:00:00[America/New_York]");
console.log(plain.toString());
console.log(zoned.toInstant().toString());
console.log(plain.add({ days: 1 }).toString());
}40date-fns vs dayjs
dayjs: tiny Moment-like chain API, immutable by default, format tokens like YYYY-MM-DD. Native Date covers instants; use either library when you need parsing, timezones, or duration helpers.
- date-fns vs dayjs
const nativeDate = new Date("2026-03-15T12:00:00Z");
const nativePlusOne = new Date(nativeDate);
nativePlusOne.setUTCDate(nativePlusOne.getUTCDate() + 1);
console.log(nativePlusOne.toISOString());
console.log("date-fns: addDays(date, 1) / format(date, \"yyyy-MM-dd\") / differenceInDays(a, b)");
console.log("dayjs: dayjs(date).add(1, \"day\").format(\"YYYY-MM-DD\") / dayjs(a).diff(b, \"day\")");Functions
12 items01First-class functions
A higher-order function takes or returns a function (map, then, onClick).
- First-class functions
function greet(name) {
return `Hello ${name}`;
}
const alsoGreet = greet;
const printName = (fn) => fn("gore");
printName(alsoGreet); // "Hello gore"02Function declarations
Own this, arguments, and .prototype. Can be new'd. Name is required.
- Function declarations
add(2, 3); // 5
function add(a, b) {
return a + b;
}
typeof add; // "function"03Function expressions
A name after function is local — good for recursion.
- Function expressions
// square(3); // TDZ if const
const square = function (n) {
return n * n;
};
const fact = function factorial(n) {
return n <= 1 ? 1 : n * factorial(n - 1);
};
fact(4); // 24
// factorial(4); // ReferenceError04Arrow functions
No .prototype; cannot be new'd. Expression body ⇒ implicit return. Objects need parens: () => ({}) No yield. Best for inline callbacks you own.
- Arrow functions
const sum = (a, b) => a + b;
const makeUser = (name) => ({ name });
// const bad = () => { name: "Ada" }; // labeled block, not an object
// new sum(); // TypeError: not a constructor05Hoisting differences
var fn = function: undefined until assigned. let/const / arrow: TDZ. In modules, a function declaration inside a block is block-scoped.
- Hoisting differences
console.log(typeof decl); // "function"
console.log(typeof expr); // "undefined" (var)
function decl() {}
var expr = function () {};
{
function inner() {}
}
// inner(); // ReferenceError in modules06arguments vs rest
Rest (...args) is a real array and works in arrows — prefer it. Arrows have no own arguments; they see the enclosing function's.
- arguments vs rest
function oldSum() {
return Array.from(arguments).reduce((a, b) => a + b, 0);
}
const newSum = (...args) => args.reduce((a, b) => a + b, 0);
oldSum(1, 2, 3); // 6
newSum(1, 2, 3); // 6
function wrapper() {
const inner = () => arguments[0];
return inner();
}
wrapper("hi"); // "hi"07Default parameters
Later defaults may read earlier params.
- Default parameters
function page(n = 1, size = 10, end = n * size) {
return { n, size, end };
}
page(); // { n: 1, size: 10, end: 10 }
page(undefined, 20); // n is 1
page(null); // n is null — not replaced08this by function kind
Arrow: this from the enclosing scope; call/apply/bind cannot change it. Object method shorthand is a regular function (lost if extracted).
- this by function kind
const obj = {
id: 1,
regular() {
return this.id;
},
nested() {
return (() => this.id)();
},
};
obj.regular(); // 1
obj.nested(); // 1
const loose = obj.regular;
// loose(); // TypeError in strict — this is undefined09IIFE
Historic module pattern; still useful for one-shot setup.
- IIFE
const token = (() => JSON.parse("{}"))();
(function (g) {
g.__boot = true;
})(globalThis);10Callbacks
The callee decides when. Use a named function if you need removeEventListener or a clear stack.
- Callbacks
function fetchData(cb) {
setTimeout(() => cb(null, { ok: true }), 100);
}
function onDone(err, data) {
console.log(err || data);
}
fetchData(onDone);11new vs arrows
Arrows cannot construct.
- new vs arrows
function User(name) {
this.name = name;
}
new User("Ada") instanceof User; // true
// new ((name) => ({ name }))(); // TypeError12name and length
fn.length counts parameters before the first default or rest.
- name and length
const named = function demo(a, b = 1, ...rest) {};
named.name; // "demo"
named.length; // 1
named.bind(null).name; // "bound demo"Closures
10 items01What a closure is
- What a closure is
function outer() {
const secret = "ok";
return function inner() {
return secret;
};
}
const fn = outer();
fn(); // "ok" — outer's frame is gone; inner still sees secret02Lexical environment
Lookup walks own env → outer env → … → global. The closure keeps that chain.
- Lexical environment
const x = "global";
function make() {
const x = "outer";
return function read() {
return x;
};
}
make()(); // "outer", not "global"03Factory functions
Returned functions from different calls do not share those locals.
- Factory functions
function makeGreeter(hi) {
return (name) => `${hi}, ${name}`;
}
const hello = makeGreeter("Hello");
const yo = makeGreeter("Yo");
hello("Ada"); // "Hello, Ada"
yo("Ada"); // "Yo, Ada"04Private counters
That is encapsulation without private class fields.
- Private counters
function createCounter(start = 0) {
let count = start;
return {
inc: () => ++count,
value: () => count,
};
}
const c = createCounter();
c.inc(); // 1
c.inc(); // 2
c.value(); // 2
c.count; // undefined05Stale closures in loops
let creates a new binding per iteration. Classic setTimeout-in-for interview.
- Stale closures in loops
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log("var", i), 0); // 3, 3, 3
}
for (let j = 0; j < 3; j++) {
setTimeout(() => console.log("let", j), 0); // 0, 1, 2
}
for (var k = 0; k < 3; k++) {
setTimeout(((n) => () => console.log("bind", n))(k), 0); // 0, 1, 2
}06Stale closures in async / UI
If this environment never updates, you see an old value (React: each render has its own state; a callback from render N reads render N).
- Stale closures in async / UI
let n = 1;
setTimeout(() => console.log(n), 50); // 2 — live binding
n = 2;
function staleFetch(id) {
return () => console.log(id); // id from this call, not "latest"
}07Module pattern
- Module pattern
const cart = (function () {
const items = [];
return {
add(item) {
items.push(item);
},
total: () => items.reduce((s, it) => s + it.price, 0),
};
})();
cart.add({ price: 10 });
cart.total(); // 10
// items stays hidden08Memory leaks
Timers, listeners, and module caches are the usual leaks. Dispose: clearInterval, removeEventListener, don't close over the node.
- Memory leaks
function attach(node) {
const huge = new Array(1e6).fill(node.innerHTML);
const onClick = () => console.log(huge.length);
node.addEventListener("click", onClick);
return () => node.removeEventListener("click", onClick);
}09Shared vs separate environments
Two outer calls → two independent environments.
- Shared vs separate environments
function pair() {
let n = 0;
return { a: () => ++n, b: () => ++n };
}
const p = pair();
p.a(); // 1
p.b(); // 2 — same n
pair().a(); // 1 — new n10Practical closures
- Practical closures
function once(fn) {
let done = false;
let result;
return function (...args) {
if (done) return result;
done = true;
result = fn.apply(this, args);
return result;
};
}
const init = once(() => "ready");
init(); // "ready"
init(); // "ready" — fn does not run againCall, Apply & Bind
11 items01How this is decided
Five rules: default, implicit, explicit, new, lexical (arrow).
- How this is decided
function show() {
return this;
}
show(); // undefined in modules/strict; globalThis in sloppy scripts
const obj = { show, tag: "obj" };
obj.show(); // implicit → this === obj02this rules in detail
Implicit: obj.fn() → this === obj. Only the last property before () counts. Explicit: call / apply / bind set this yourself. new: this is the newly created instance. Arrow: this is lexical — call/apply/bind cannot change it.
- this rules in detail
const nested = { inner: { show } };
nested.inner.show(); // this === nested.inner, not nested
const detached = obj.show;
detached(); // default binding — this is NOT obj03call — invoke now, args listed
Primitive thisArg is boxed (except in strict mode, where it stays as-is). Use when you already have individual arguments.
- call — invoke now, args listed
function deliver(order, time) {
return `${this.restaurant} delivers ${order} at ${time} from ${this.location}`;
}
const mcd = { restaurant: "McDonald's", location: "MG Road" };
deliver.call(mcd, "Burger", "6:00 PM");04apply — invoke now, args as an array
Classic trick: Math.max.apply(null, nums) before spread existed. Today: fn.call(thisArg, ...arr) or Math.max(...nums).
- apply — invoke now, args as an array
const dominos = { restaurant: "Domino's", location: "FC Road" };
deliver.apply(dominos, ["Pizza", "7:00 PM"]);
Math.max.apply(null, [3, 9, 1]); // 9
Math.max(...[3, 9, 1]); // 9 — modern equivalent05bind — new function, this locked
Original is unchanged. Later call/apply on the bound fn cannot replace this (except as a constructor). Extra bind args are prepended (partial application).
- bind — new function, this locked
const subway = { restaurant: "Subway", location: "JM Road" };
const subwayDelivery = deliver.bind(subway);
subwayDelivery("Sub", "5:30 PM");
const burgerAt6 = deliver.bind(mcd, "Burger");
burgerAt6("6:00 PM");06call vs apply vs bind
None of them mutate the original function.
- call vs apply vs bind
const ctx = { n: 2 };
function scale(x, y) {
return (x + y) * this.n;
}
scale.call(ctx, 3, 4); // 14
scale.apply(ctx, [3, 4]); // 14
const bound = scale.bind(ctx, 3);
bound(4); // 1407Lost this on method extract
setTimeout, addEventListener, map, and React props all do this.
- Lost this on method extract
const counter = {
n: 0,
inc() {
this.n += 1;
return this.n;
},
};
const loose = counter.inc;
// loose(); // TypeError — this is undefined, cannot read n
setTimeout(counter.inc, 0); // this is not counter08Bound methods as callbacks
Same bound reference is required for removeEventListener.
- Bound methods as callbacks
const incBound = counter.inc.bind(counter);
setTimeout(incBound, 0);
button.addEventListener("click", incBound);
button.removeEventListener("click", incBound); // works — same reference
const onClick = () => counter.inc(); // also fine; this inside inc is counter09bind vs arrow
Arrow: no own this / arguments / prototype; cannot be new'd; cheaper if you only need lexical this. Prefer arrows for inline callbacks you own; prefer bind when adapting an existing method or fixing arguments.
- bind vs arrow
const widget = {
id: 7,
bound: function () {
return this.id;
}.bind({ id: 99 }),
arrow: () => this,
};
widget.bound(); // 99 — bind wins over implicit obj.bound()
// widget.arrow() uses the this of the enclosing scope, not widget10Polyfill-level bind
- Polyfill-level bind
Function.prototype.myBind = function (thisArg, ...preset) {
const fn = this;
function bound(...later) {
const ctx = new.target ? this : thisArg;
return fn.apply(ctx, preset.concat(later));
}
if (fn.prototype) bound.prototype = Object.create(fn.prototype);
return bound;
};
function Person(name) {
this.name = name;
}
const BoundPerson = Person.myBind({ ignored: true });
new BoundPerson("Ada").name; // "Ada" — new.target path
BoundPerson("Lin"); // thisArg path (sloppy: sets global name)11Strict vs sloppy thisArg
In strict mode (and ES modules), it stays null/undefined. Objects are used as-is; primitives are boxed in sloppy functions.
- Strict vs sloppy thisArg
function who() {
return this;
}
who.call(null); // globalThis in sloppy; null in strict
who.call(42); // Number(42) in sloppy; 42 in strictCurrying
10 items01What is currying
Each call returns a new function that closes over args collected so far. Same result as the original, different calling shape. Named after Haskell Curry.
- What is currying
function add(a, b, c) {
return a + b + c;
}
const curriedAdd = (a) => (b) => (c) => a + b + c;
add(1, 2, 3); // 6
curriedAdd(1)(2)(3); // 6
const add1 = curriedAdd(1);
add1(2)(3); // 6 — reuse the partially filled function02Manual curry
The innermost function does the real work; outer levels only capture arguments via closure.
- Manual curry
function volume(l) {
return function (w) {
return function (h) {
return l * w * h;
};
};
}
volume(2)(3)(4); // 24
const base = volume(2)(3);
base(4); // 24
base(10); // 6003Generic curry helper
Extra args in one call still count (not strictly unary). Pitfall: rest params and defaults make fn.length lie.
- Generic curry helper
function curry(fn) {
return function curried(...args) {
if (args.length >= fn.length) return fn.apply(this, args);
return (...next) => curried.apply(this, args.concat(next));
};
}
function multiply(a, b, c) {
return a * b * c;
}
const curriedMul = curry(multiply);
curriedMul(2)(3)(4); // 24
curriedMul(2, 3)(4); // 24
curriedMul(2)(3, 4); // 2404Curry vs partial application
Partial: pre-fill some args now, accept the rest later — not necessarily one-at-a-time. Function.prototype.bind is partial application, not currying.
- Curry vs partial application
function greet(hi, name, end) {
return `${hi}, ${name}${end}`;
}
const sayHello = greet.bind(null, "Hello"); // still needs name + end
sayHello("Ada", "!"); // "Hello, Ada!"
const curryGreet = (hi) => (name) => (end) => `${hi}, ${name}${end}`;
curryGreet("Hi")("Ada")("."); // one argument per call05Placeholders
Incoming values fill holes left-to-right, then append leftover args.
- Placeholders
const _ = Symbol("_");
function mergeArgs(prev, next) {
const extra = [...next];
const merged = prev.map((a) => (a === _ && extra.length ? extra.shift() : a));
return merged.concat(extra);
}
function curryHole(fn) {
const gather = (...args) => {
const slot = args.slice(0, fn.length);
if (slot.length >= fn.length && !slot.includes(_)) return fn(...slot);
return (...more) => gather(...mergeArgs(args, more));
};
return gather;
}
const divide = (a, b) => a / b;
const half = curryHole(divide)(_, 2);
half(10); // 5
curryHole(divide)(10)(2); // 506Real use cases
Curry once, pass the unary result to map / filter / addEventListener.
- Real use cases
const map = (fn) => (xs) => xs.map(fn);
const get = (key) => (obj) => obj[key];
const names = map(get("name"));
names([{ name: "Ada" }, { name: "Lin" }]); // ["Ada", "Lin"]
const logAt = (level) => (msg) => console.log(`[${level}] ${msg}`);
const error = logAt("error");
error("disk full");
const onClick = (fn) => (el) => el.addEventListener("click", fn);07compose
Works cleanly when each step is unary — which currying gives you.
- compose
const compose = (...fns) => (x) => fns.reduceRight((v, f) => f(v), x);
const double = (n) => n * 2;
const inc = (n) => n + 1;
compose(double, inc)(3); // 8 — double(inc(3))08pipe
Same idea as compose, usually easier to read as a data pipeline.
- pipe
const pipe = (...fns) => (x) => fns.reduce((v, f) => f(v), x);
pipe(inc, double)(3); // 8 — double(inc(3))
pipe(get("name"), (s) => s.toUpperCase())({ name: "ada" }); // "ADA"09Infinite curry vs fixed arity
That is a running accumulator, not classic curry.
- Infinite curry vs fixed arity
function sum(a) {
const next = (b) => (b === undefined ? a : sum(a + b));
next.valueOf = () => a;
return next;
}
sum(1)(2)(3)(); // 6
+sum(1)(2)(3); // 6 via valueOf10Pitfalls
fn.length is 0 for (...args) and skips params after the first default. Debugging is easier if you keep a named inner function in the helper.
- Pitfalls
function withDefault(a, b = 1) {
return a + b;
}
withDefault.length; // 1 — curry would fire too early
function resty(...xs) {
return xs;
}
resty.length; // 0Promises
6 items01A JavaScript Promise is an object that represents the eventu
// A JavaScript Promise has three states in its lifecycle:02Pending
The async operation is still in progress. Neither resolve nor reject has been called.
- Pending
03Fulfilled
resolve(value) was called.
- Fulfilled
04.then()
05Rejected
reject(error) was called.
- Rejected
06.catch()
// Need : used to handel asynchronous operations
// Benefits:
// Improved code readability and maintainability by handling asynchronous operations asynchronously.
// Chaining of asynchronous operations for a more fluid flow.
// Error handling for potential issues during asynchronous execution.
fetch("https://api.example.com/data")
.then((response) => response.json())
.then((data) => {
console.log(data);
// Process the data
})
.catch((error) => {
console.error(error);
// Handle errors
});
// promise chaning
// the process of executing a sequence of asynchronous tasks one after another using promise
// .then(){}
// .then(){}
// .then(){}
// Promises and async/await are both tools for handling asynchronous operations in JavaScript,
// but they differ in syntax and approach.
// Promises
// Represent the eventual result of an asynchronous operation.
// Have three states: pending, fulfilled, or rejected.
// Use .then() for successful outcomes and .catch() for errors.
// Can lead to complex chains of .then() and .catch(), known as "callback hell."
// Async/Await
// Built on top of promises, providing a more synchronous-like syntax.
// async declares a function that returns a promise.
// await pauses execution until the promise resolves or rejects.
// Makes asynchronous code easier to read and debug.
// Uses try...catch for error handling, similar to synchronous code.Errors
13 items01Error object
You can throw any value — don't; you lose the stack.
- Error object
const err = new Error("boom");
err.name; // "Error"
err.message; // "boom"
err.stack; // engine-specific frames02ReferenceError
Different from a declared variable whose value is undefined.
- ReferenceError
// console.log(missing); // missing is not defined
// console.log(x); // Cannot access 'x' before initialization
let x = 5;
typeof missing; // "undefined" — typeof is safe for undeclared names03TypeError
- TypeError
// null.f(); // Cannot read properties of null
// (5).toUpperCase(); // not a function
const n = 1;
// n = 2; // Assignment to constant variable
Object.freeze({ a: 1 }).a = 2; // TypeError in strict; ignored in sloppy04SyntaxError
You cannot catch it in the same file. You can catch it from JSON.parse, eval, or new Function.
- SyntaxError
// if (true { } // Unexpected token '{'
try {
JSON.parse("{");
} catch (e) {
e instanceof SyntaxError; // true
}05RangeError
Deep recursion is "Maximum call stack size exceeded" (V8). Firefox may use InternalError.
- RangeError
// new Array(-1);
// (10).toPrecision(500);
function recurse(k) {
return recurse(k + 1);
}06URIError
An EvalError exists for history; engines almost never throw it now.
- URIError
decodeURIComponent("a%"); // URI malformed07throw
Prefer new SomeError(msg) so callers can use instanceof and still have a stack.
- throw
function parseAge(raw) {
const age = Number(raw);
if (Number.isNaN(age)) throw new TypeError("age must be numeric");
if (age < 0) throw new RangeError("age must be >= 0");
return age;
}
parseAge("21"); // 2108try / catch / finally
A return in finally wins over try. Optional catch binding: catch { } (ES2019).
- try / catch / finally
function read() {
try {
return parseAge("no");
} catch (e) {
console.log(e.message);
return 0;
} finally {
console.log("cleanup");
}
}
read(); // logs message, then "cleanup", returns 009Rethrow
No catch-if syntax — use if + throw.
- Rethrow
try {
parseAge(-1);
} catch (e) {
if (e instanceof RangeError) console.log("bad range");
else throw e;
}10Async errors
await inside try/catch (or .catch). throw in async rejects the promise.
- Async errors
try {
setTimeout(() => {
throw new Error("late"); // not caught here
}, 0);
} catch (e) {
// never runs — the throw is inside the timer
}
async function load() {
try {
await Promise.reject(new Error("network"));
} catch (e) {
console.log(e.message); // "network"
}
}11Custom errors
Keep instanceof working.
- Custom errors
class ValidationError extends Error {
constructor(message, field) {
super(message);
this.name = "ValidationError";
this.field = field;
}
}
try {
throw new ValidationError("email required", "email");
} catch (e) {
e instanceof ValidationError; // true
e instanceof Error; // true
}12Error.cause
DevTools shows the chain; read it later as err.cause.
- Error.cause
try {
JSON.parse("{");
} catch (e) {
throw new Error("invalid config", { cause: e });
}13AggregateError
Promise.any rejects with this when every promise rejects. errors is the array of reasons.
- AggregateError
Promise.any([Promise.reject("a"), Promise.reject("b")]).catch((e) => {
e instanceof AggregateError; // true
e.errors; // ["a", "b"]
});
new AggregateError([new Error("x")], "batch failed").errors.length; // 1ES6
10 items01Here’s a concise overview of ES6 (ECMAScript 2015) features
02Let and Const
- Let and Const
// let is mutable, const is immutable (for primitive values).
let a = 10;
a = 20;
const b = 30;
// b = 40; Error03Arrow Functions
- Arrow Functions
const sum = (a, b) => a + b;
console.log(sum(2, 3)); // 504Template Literals
- Template Literals
const Name = "Gore";
console.log(`Hello, ${Name}!`);05Destructuring Assignment
- Destructuring Assignment
const userOne = { name: "Gore", age_: 25 };
const { name, age_ } = userOne;
// Array Destructuring
const nums = [1, 2];
const [x, y] = nums;
const numbers = [1, 2, 3, 4, 5];
const [first, second, ...rest] = numbers;
console.log(first); // 1
console.log(second); // 2
console.log(rest); // [3, 4, 5]06Default Parameters
- Default Parameters
function greet(name = "Guest") {
console.log(`Hello, ${name}`);
}
greet(); // Hello, Guest07Rest and Spread Operators ... to collect or expand values
- Rest and Spread Operators ... to collect or expand values.
// Rest
function sum(...nums) {
return nums.reduce((a, b) => a + b, 0);
}
// Spread
const arr1 = [1, 2];
const arr2 = [...arr1, 3, 4];
// Modules
// export and import to share code.
// utils.js
export const PI = 3.14;
// main.js
import { PI } from "./utils.js";08Promises
- Promises
const fetchData = () =>
new Promise((resolve) => {
setTimeout(() => resolve("Done"), 1000);
});
fetchData().then(console.log);09For...of Loop
- For...of Loop
for (const num of [1, 2, 3]) {
console.log(num);
}10Map and Set
- Map and Set
const set = new Set([1, 2, 2]); // {1, 2}
const map = new Map();
map.set("key", "value");Regular Expressions
9 items01Key Regex Building Blocks
02Character Classes
- Character Classes
// \d → digit (0–9)
// \w → word char (a-zA-Z0-9_)
// \s → whitespace
// . → any character except newline
// [...] → match any listed chars
// ------> [aeiou] → matches any vowel
console.log(/[aeiou]/.test("cat")); // true03Quantifiers
- Quantifiers
// + → 1 or more
// * → 0 or more
// ? → 0 or 1 (optional)
// {n} → exactly n times
// {n,} → at least n times
// {n,m} → between n and m times
console.log(/\d{2}/.test("ab12cd")); // true (2 digits)04Anchors
- Anchors
// ^ → start of string
// $ → end of string
console.log(/^hello/.test("hello world")); // true
console.log(/world$/.test("hello world")); // true05Groups & Alternation
- Groups & Alternation
// (abc) → group
// | → OR
console.log(/cat|dog/.test("dog")); // true06Escaping
- Escaping
// Match special chars (. ^ $ * + ? { } [ ] | ( )), escape with \.
console.log(/\./.test("file.txt")); // true07Email
08Phone Number (basic, 10 digits)
- Phone Number (basic, 10 digits)
09Date (YYYY-MM-DD)
- Date (YYYY-MM-DD)
const str = `lorem ipsum20-02-1000 dolor 30/07/1999 sit amet 30/07/19999lorem ipsum dolor sit amet lorem ipsum dolor sit
ametvlorem20-02-1999 ipsum dolor sit ametlorem ipsum dolor20/1999 sit ametlorem
ipsum dolor sit amet lorem ipsum dolor sit amet`;
console.log(/\d{2,4}[-/]\d{2}[-/]\d{2,4}/.test(str));
console.log(str.replace(/\d{2,4}[-/]\d{2}[-/]\d{2,4}/g, "Date"));
// g to replace all dates , if not g then it will replace 1st one onlyStorage
25 items01When to use each
sessionStorage — this tab only; dies when the tab closes. Cookies — sent on HTTP requests; use for auth the server must see. IndexedDB — large structured data, files, offline caches.
- When to use each
const pick = {
theme: "localStorage",
wizardStep: "sessionStorage",
sessionId: "cookie (server-set, HttpOnly)",
offlineNotes: "IndexedDB",
};
console.log(pick.theme);02localStorage set and get
Survives refresh and browser restart. All values are strings. Missing keys return null, not undefined.
- localStorage set and get
localStorage.setItem("theme", "dark");
const theme = localStorage.getItem("theme"); // "dark"
console.log(theme);
console.log(localStorage.getItem("missing")); // null03localStorage remove and clear
clear() wipes every key for this origin. Prefer removeItem so you do not delete unrelated keys.
- localStorage remove and clear
localStorage.setItem("a", "1");
localStorage.setItem("b", "2");
localStorage.removeItem("a");
console.log(localStorage.getItem("a")); // null04localStorage key and length
key(i) reads the name at that index. Index order is not something you should rely on.
- localStorage key and length
localStorage.setItem("user", "gore");
console.log(localStorage.length);
console.log(localStorage.key(0));
for (let i = 0; i < localStorage.length; i++) {
const k = localStorage.key(i);
console.log(k, localStorage.getItem(k));
}05sessionStorage tab scope
A duplicate tab usually gets a copy; a new tab starts empty. Closing the tab deletes it. Refresh keeps it.
- sessionStorage tab scope
sessionStorage.setItem("step", "2");
console.log(sessionStorage.getItem("step")); // "2"
sessionStorage.removeItem("step");06Values are always strings
[object Object] is the classic bug. Always JSON.stringify objects.
- Values are always strings
localStorage.setItem("count", 5);
console.log(localStorage.getItem("count") === "5"); // true
localStorage.setItem("on", true);
console.log(localStorage.getItem("on")); // "true"
localStorage.setItem("bad", { a: 1 });
console.log(localStorage.getItem("bad")); // "[object Object]"07JSON serialize for objects
Guard parse — empty, null, or corrupt strings throw.
- JSON serialize for objects
const user = { id: 1, name: "Gore" };
localStorage.setItem("user", JSON.stringify(user));
const raw = localStorage.getItem("user");
const parsed = raw ? JSON.parse(raw) : null;
console.log(parsed.name); // Gore08JSON serialize pitfalls
Date becomes an ISO string. Map/Set become {}. Functions and symbols are omitted. Circular refs throw. NaN and Infinity become null.
- JSON serialize pitfalls
console.log(JSON.stringify({ a: undefined })); // "{}"
console.log(JSON.stringify([undefined])); // "[null]"
console.log(JSON.stringify(new Date("2026-01-01"))); // '"2026-01-01T00:00:00.000Z"'
console.log(JSON.stringify(new Map([["a", 1]]))); // "{}"
console.log(JSON.stringify({ n: NaN })); // '{"n":null}'
const cycle = {};
cycle.self = cycle;
try {
JSON.stringify(cycle);
} catch (err) {
console.log(err.name); // TypeError
}09QuotaExceededError
Writes can throw QuotaExceededError (or a DOMException). Always try/catch.
- QuotaExceededError
try {
localStorage.setItem("cache", "x".repeat(10_000_000));
} catch (err) {
if (err.name === "QuotaExceededError") {
localStorage.removeItem("cache");
}
}10Same-origin isolation
https://a.com cannot read http://a.com or https://b.com. localhost:3000 is not shared with :3001. Subdomains need cookie Domain to share.
- Same-origin isolation
console.log(location.origin); // e.g. "http://localhost:3000"11storage event
The writing tab does not get the event. Other tab: localStorage.setItem(...). sessionStorage almost never notifies other tabs (tab-scoped).
- storage event
window.addEventListener("storage", (e) => {
console.log(e.key, e.oldValue, e.newValue, e.url);
console.log(e.storageArea === localStorage);
});12Read document.cookie
HttpOnly cookies are invisible to JS. There is no API to read attributes (Path, SameSite) back out.
- Read document.cookie
console.log(document.cookie); // "theme=dark; locale=en"
const cookies = Object.fromEntries(
document.cookie
.split("; ")
.filter(Boolean)
.map((pair) => pair.split("=").map(decodeURIComponent)),
);
console.log(cookies.theme);13Write document.cookie
Default: session cookie (deleted when the browser closes), current path.
- Write document.cookie
document.cookie = "theme=dark";
document.cookie = "locale=en";
console.log(document.cookie); // both still present14Cookie expires and max-age
max-age is seconds from now (usually preferred). max-age=0 (or a past expires) deletes the cookie.
- Cookie expires and max-age
document.cookie = `token=abc; max-age=${60 * 60 * 24 * 7}`; // 7 days
document.cookie = `old=1; expires=${new Date(Date.now() + 864e5).toUTCString()}`;15Cookie path and domain
Use Path=/ for the whole site. Domain=example.com shares across subdomains (leading dot is optional now).
- Cookie path and domain
document.cookie = "theme=dark; Path=/";
document.cookie = "theme=dark; Domain=example.com; Path=/";16Secure HttpOnly SameSite
HttpOnly — JS cannot read it; only the server can set this (Set-Cookie header). SameSite=Lax|Strict|None (None requires Secure). Stops most CSRF cookie sends.
- Secure HttpOnly SameSite
document.cookie = "prefs=1; Path=/; Secure; SameSite=Lax";
console.log(document.cookie.includes("prefs"));17Encode cookie values
Encode on write, decode on read. Cookie names should stay simple tokens.
- Encode cookie values
const value = "Gore; admin=true";
document.cookie = `name=${encodeURIComponent(value)}; Path=/`;
const match = document.cookie.match(/(?:^|; )name=([^;]*)/);
console.log(match ? decodeURIComponent(match[1]) : null);18Delete a cookie
Path and Domain must match the original or the browser will not delete it.
- Delete a cookie
document.cookie = "theme=; Path=/; max-age=0";
document.cookie = "theme=; Domain=example.com; Path=/; max-age=0";19Cookies vs Web Storage
Web Storage: ~5MB, never sent automatically, JS-only. Never put secrets in localStorage — any XSS can read them.
- Cookies vs Web Storage
const sentWithEveryRequest = "cookies";
const staysInTheBrowser = "localStorage / sessionStorage / IndexedDB";
console.log(sentWithEveryRequest, staysInTheBrowser);20IndexedDB open
onupgradeneeded runs when the version is new or higher.
- IndexedDB open
const openReq = indexedDB.open("notes-db", 1);
openReq.onerror = () => console.error(openReq.error);
openReq.onsuccess = () => {
const db = openReq.result;
console.log(db.name, db.version);
db.close();
};21IndexedDB object store
Create them only inside onupgradeneeded. keyPath uses a field on the value. autoIncrement assigns keys.
- IndexedDB object store
const openV1 = indexedDB.open("notes-db", 1);
openV1.onupgradeneeded = () => {
const db = openV1.result;
if (!db.objectStoreNames.contains("notes")) {
const store = db.createObjectStore("notes", { keyPath: "id" });
store.createIndex("byTitle", "title", { unique: false });
}
};22IndexedDB put and add
put upserts; add fails if the key exists. Work must happen while the transaction is active (no awaiting extra I/O in between).
- IndexedDB put and add
function putNote(db, note) {
return new Promise((resolve, reject) => {
const tx = db.transaction("notes", "readwrite");
tx.oncomplete = () => resolve();
tx.onerror = () => reject(tx.error);
tx.objectStore("notes").put(note); // putNote(db, { id: "n1", title: "Fetch" })
});
}23IndexedDB get
getAll() pulls a snapshot.
- IndexedDB get
function getNote(db, id) {
return new Promise((resolve, reject) => {
const tx = db.transaction("notes", "readonly");
const req = tx.objectStore("notes").get(id);
req.onsuccess = () => resolve(req.result);
req.onerror = () => reject(req.error); // const note = await getNote(db, "n1")
});
}24IndexedDB delete and cursor
openCursor walks records without loading all.
- IndexedDB delete and cursor
function deleteNote(db, id) {
return new Promise((resolve, reject) => {
const tx = db.transaction("notes", "readwrite");
tx.oncomplete = () => resolve();
tx.onerror = () => reject(tx.error);
tx.objectStore("notes").delete(id);
});
}
function walkNotes(db, onRow) {
const tx = db.transaction("notes", "readonly");
tx.objectStore("notes").openCursor().onsuccess = (e) => {
const cursor = e.target.result;
if (!cursor) return;
onRow(cursor.value);
cursor.continue();
};
}25Storage quotas
persist() asks the browser not to evict the origin under storage pressure.
- Storage quotas
const { usage, quota } = await navigator.storage.estimate();
console.log(`using ${usage} / ${quota} bytes`);
const persisted = await navigator.storage.persist();
console.log("persistent?", persisted);
console.log(await navigator.storage.persisted());Fetch & HTTP
25 items01fetch GET
The promise rejects only on network failure, not on 404/500.
- fetch GET
const res = await fetch("https://api.example.com/users");
const data = await res.json();
console.log(data);02Response.ok
Always check it before trusting the body. status / statusText are the raw HTTP code and reason.
- Response.ok
const res2 = await fetch("/api/user");
if (!res2.ok) {
throw new Error(`${res2.status} ${res2.statusText}`);
}
console.log(res2.status); // 20003Parse JSON
Empty or non-JSON bodies throw. Also: text(), blob(), arrayBuffer(), formData().
- Parse JSON
const res3 = await fetch("/api/me");
const me = await res3.json();
console.log(me.id);04POST JSON
JSON.stringify the object yourself.
- POST JSON
const created = await fetch("/api/notes", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ title: "Fetch", done: false }),
});
console.log(created.ok, created.status); // 20105Custom headers
Forbidden headers (Cookie, Host, Origin, …) are controlled by the browser.
- Custom headers
const headers = new Headers();
headers.set("Accept", "application/json");
headers.set("X-Request-Id", crypto.randomUUID());
const res5 = await fetch("/api/notes", { headers });
console.log(res5.headers.get("content-type"));06Query parameters
- Query parameters
const url = new URL("/api/notes", location.origin);
url.searchParams.set("q", "fetch cors");
url.searchParams.set("page", "1");
const list = await fetch(url);
console.log(url.href); // /api/notes?q=fetch+cors&page=1
console.log(await list.json());07AbortController
abort() rejects the fetch with an AbortError. One controller can abort several fetches that share the same signal.
- AbortController
const ac = new AbortController();
document.querySelector("#cancel")?.addEventListener("click", () => ac.abort());
try {
const res7 = await fetch("/api/slow", { signal: ac.signal });
console.log(await res7.text());
} catch (err) {
if (err.name === "AbortError") console.log("cancelled");
}08Timeout pattern
Abort after N ms, then always clear the timer.
- Timeout pattern
async function fetchWithTimeout(resource, ms = 8000, options = {}) {
const ac = new AbortController();
const timer = setTimeout(() => ac.abort(), ms);
try {
return await fetch(resource, { ...options, signal: ac.signal });
} finally {
clearTimeout(timer);
}
}
const timed = await fetchWithTimeout("/api/data", 3000);
console.log(timed.ok);09Retry with backoff
Do not blindly retry 4xx or POST without care. Backoff: wait base * 2^attempt (and optionally add jitter).
- Retry with backoff
async function fetchRetry(resource, { retries = 3, base = 300, ...options } = {}) {
let lastErr;
for (let i = 0; i <= retries; i++) {
try {
const res = await fetch(resource, options);
if (res.ok || (res.status >= 400 && res.status < 500)) return res;
lastErr = new Error(`HTTP ${res.status}`);
} catch (err) {
lastErr = err;
}
if (i < retries) {
await new Promise((r) => setTimeout(r, base * 2 ** i));
}
}
throw lastErr;
}
const retried = await fetchRetry("/api/flaky");
console.log(retried.status);10FormData uploads
Append strings or File/Blob values. Use this for file inputs — not JSON.stringify.
- FormData uploads
const form = new FormData();
form.append("title", "shot");
form.append("file", document.querySelector("#file")?.files[0]);
const uploaded = await fetch("/api/upload", { method: "POST", body: form });
console.log(uploaded.ok);11FormData Content-Type
Setting application/json or a bare multipart type breaks the upload.
- FormData Content-Type
const fd = new FormData();
fd.append("q", "notes");
await fetch("/api/search", {
method: "POST",
body: fd,
// headers: { "Content-Type": "multipart/form-data" } // ← missing boundary, broken
});12credentials
include — cookies on cross-origin too (server must allow credentials). omit — never send cookies.
- credentials
await fetch("/api/me", { credentials: "same-origin" });
await fetch("https://api.other.com/me", { credentials: "include" });
await fetch("/api/public", { credentials: "omit" });13CORS mental model
curl is unaffected. Credentials cannot use *. They need a concrete origin + Allow-Credentials: true.
- CORS mental model
const corsRes = await fetch("https://api.other.com/data");
console.log(corsRes.ok);14Simple vs preflight
Anything else (PUT, JSON Content-Type, custom headers) → preflight OPTIONS first. Preflight asks: Access-Control-Request-Method / Headers; server answers Allow-*.
- Simple vs preflight
await fetch("https://api.other.com/notes", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ title: "hi" }),
});
console.log("OPTIONS preflight runs first, then POST if it succeeds");15fetch mode
no-cors — you get an opaque response (status 0, body unreadable). Rarely useful. same-origin — throw if the URL is cross-origin.
- fetch mode
await fetch("/api/me", { mode: "same-origin" });
await fetch("https://cdn.example.com/hit", { mode: "no-cors" }); // opaque16Network vs HTTP errors
404 / 500 → fetch resolves; you must check response.ok.
- Network vs HTTP errors
try {
const res16 = await fetch("/api/missing");
if (!res16.ok) console.log("HTTP error", res16.status);
} catch (err) {
console.log("network / CORS / abort", err.name);
}17Streaming text
Read chunks before the full payload arrives. Useful for SSE-like text, logs, or large files. json() waits for the whole body.
- Streaming text
const res17 = await fetch("/api/stream");
const reader = res17.body.getReader();
const decoder = new TextDecoder();
let text = "";
for (;;) {
const { done, value } = await reader.read();
if (done) break;
text += decoder.decode(value, { stream: true });
}
console.log(text);18response.clone
json() then text() throws. clone() before reading if you need two consumers.
- response.clone
const res18 = await fetch("/api/me");
const copy = res18.clone();
console.log(await res18.json());
console.log(await copy.text());19PUT PATCH DELETE
DELETE often has no body; PATCH/PUT usually send JSON.
- PUT PATCH DELETE
await fetch("/api/notes/1", { method: "DELETE" });
await fetch("/api/notes/1", {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ done: true }),
});
await fetch("/api/notes/1", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ title: "Fetch", done: true }),
});20URLSearchParams body
fetch sets the Content-Type when the body is URLSearchParams.
- URLSearchParams body
const params = new URLSearchParams({ email: "a@b.com", remember: "1" });
await fetch("/login", { method: "POST", body: params });21Blob download
Object URLs can trigger a download.
- Blob download
const res21 = await fetch("/api/report.pdf");
const blob = await res21.blob();
const href = URL.createObjectURL(blob);
const a = Object.assign(document.createElement("a"), { href, download: "report.pdf" });
a.click();
URL.revokeObjectURL(href);22cache option
no-store — always hit the network. reload — network then update cache. force-cache / only-if-cached — prefer cache.
- cache option
await fetch("/api/config", { cache: "no-store" });
await fetch("/icons/app.svg", { cache: "force-cache" });23redirect option
manual — you see the redirect response. error — reject on redirect.
- redirect option
const res23 = await fetch("/old-path", { redirect: "follow" });
console.log(res23.redirected, res23.url);24Parallel requests
All fail if one rejects. Promise.allSettled if you want partial results.
- Parallel requests
const [users, notes] = await Promise.all([
fetch("/api/users").then((r) => r.json()),
fetch("/api/notes").then((r) => r.json()),
]);
console.log(users.length, notes.length);25Error handling pattern
Check ok for HTTP errors. Read an error payload when the server sends JSON errors.
- Error handling pattern
async function api(path, options) {
let res;
try {
res = await fetch(path, options);
} catch (err) {
if (err.name === "AbortError") throw err;
throw new Error("Network error");
}
const body = await res.json().catch(() => null);
if (!res.ok) throw new Error(body?.message ?? `HTTP ${res.status}`);
return body;
}
const note = await api("/api/notes/1");
console.log(note);Web APIs
20 items01IntersectionObserver
Use for lazy images, infinite scroll, and "was this section seen?".
- IntersectionObserver
const io = new IntersectionObserver((entries) => {
for (const entry of entries) {
if (entry.isIntersecting) {
console.log("visible", entry.target, entry.intersectionRatio);
}
}
});
io.observe(document.querySelector("#card"));02IntersectionObserver options
rootMargin — CSS-like grow/shrink. threshold — 0..1 (or an array). 0.25 = callback when 25% is visible.
- IntersectionObserver options
const io2 = new IntersectionObserver(
(entries) => {
entries.forEach((e) => e.target.classList.toggle("in", e.isIntersecting));
},
{ root: document.querySelector("#scroll"), rootMargin: "100px 0px", threshold: [0, 0.25, 1] },
);
io2.observe(document.querySelector("img[data-src]"));03unobserve and disconnect
disconnect() stops every target at once. After a one-shot lazy-load, unobserve so the callback stops firing.
- unobserve and disconnect
const img = document.querySelector("img[data-src]");
const lazy = new IntersectionObserver(([entry], obs) => {
if (!entry.isIntersecting) return;
entry.target.src = entry.target.dataset.src;
obs.unobserve(entry.target);
});
lazy.observe(img);04ResizeObserver
Prefer this over measuring in a window resize listener. Cleanup: ro.unobserve(el) or ro.disconnect().
- ResizeObserver
const ro = new ResizeObserver((entries) => {
for (const entry of entries) {
const { inlineSize, blockSize } = entry.contentBoxSize[0];
console.log(entry.target, inlineSize, blockSize);
}
});
ro.observe(document.querySelector("#sidebar"));05MutationObserver
Use for integrating with third-party widgets — not as a React state substitute.
- MutationObserver
const mo = new MutationObserver((mutations) => {
for (const m of mutations) {
console.log(m.type, m.target, m.addedNodes);
}
});
mo.observe(document.querySelector("#list"), { childList: true });06MutationObserver options
attributes — attr changes (filter with attributeFilter). subtree — watch descendants. characterData — text node changes. disconnect, then takeRecords() to drain queued mutations.
- MutationObserver options
const mo6 = new MutationObserver(() => {});
mo6.observe(document.body, {
childList: true,
subtree: true,
attributes: true,
attributeFilter: ["class", "hidden"],
characterData: false,
});
const pending = mo6.takeRecords();
mo6.disconnect();
console.log(pending.length);07Create a Web Worker
Offload CPU work (parse, crypto, canvas pixel math) so the UI stays responsive.
- Create a Web Worker
const worker = new Worker("/worker.js", { type: "module" });
console.log(worker); // Dedicated: one page. SharedWorker: many tabs.08postMessage
Transferables (ArrayBuffer) move ownership instead of copying. worker.js: self.onmessage = (e) => self.postMessage({ result: e.data.n * 2 });
- postMessage
const fibWorker = new Worker("/worker.js");
fibWorker.postMessage({ type: "fib", n: 40 });
fibWorker.onmessage = (e) => console.log("result", e.data);09Worker error and terminate
terminate() kills the worker from the page; self.close() from inside.
- Worker error and terminate
const w = new Worker("/worker.js");
w.onerror = (e) => console.error(e.message, e.filename, e.lineno);
w.onmessageerror = (e) => console.error("clone failed", e);
w.terminate();10requestIdleCallback
deadline.timeRemaining() is leftover idle ms. Do not do long tasks here.
- requestIdleCallback
const tasks = [() => console.log("prefetch"), () => console.log("index")];
const idleId = requestIdleCallback((deadline) => {
while (deadline.timeRemaining() > 0 && tasks.length) {
tasks.shift()();
}
});
console.log(idleId);11Idle timeout option
cancelIdleCallback cancels a pending id. Safari support is late — feature-detect.
- Idle timeout option
const idle2 = requestIdleCallback(
(deadline) => {
console.log("idle or forced", deadline.didTimeout, deadline.timeRemaining());
},
{ timeout: 2000 },
);
cancelIdleCallback(idle2);
if (typeof requestIdleCallback !== "function") {
setTimeout(() => {}, 1);
}12requestAnimationFrame
Use for animations and visual sync. One callback per frame; batch DOM reads, then writes, to avoid layout thrash.
- requestAnimationFrame
let rafId = requestAnimationFrame(function tick(ts) {
console.log("frame", ts);
rafId = requestAnimationFrame(tick);
});13cancelAnimationFrame
- cancelAnimationFrame
let x = 0;
function slide(ts) {
x += 2;
box.style.transform = `translateX(${x}px)`;
if (x < 200) rafSlide = requestAnimationFrame(slide);
}
const box = document.querySelector("#box");
let rafSlide = requestAnimationFrame(slide);
cancelAnimationFrame(rafSlide);14matchMedia
Prefer this over reading window.innerWidth for breakpoint logic.
- matchMedia
const mq = window.matchMedia("(min-width: 768px)");
console.log(mq.media, mq.matches); // true on tablet/desktop
if (mq.matches) document.body.classList.add("is-wide");15matchMedia change
Use addEventListener("change") — addListener is deprecated. Cleanup: dark.removeEventListener("change", syncTheme).
- matchMedia change
const dark = window.matchMedia("(prefers-color-scheme: dark)");
function syncTheme(e) {
document.documentElement.dataset.theme = e.matches ? "dark" : "light";
}
syncTheme(dark);
dark.addEventListener("change", syncTheme);16Visibility API
"visible" | "hidden" (prerender/unloaded exist in older notes).
- Visibility API
console.log(document.hidden);
console.log(document.visibilityState); // "visible" | "hidden"
document.addEventListener("visibilitychange", () => {
console.log("now", document.visibilityState);
});17Pause when hidden
Saves CPU and battery; resume on visible.
- Pause when hidden
let poll;
function startPoll() {
poll = setInterval(() => fetch("/api/ping"), 10_000);
}
startPoll();
document.addEventListener("visibilitychange", () => {
if (document.hidden) {
clearInterval(poll);
document.querySelector("video")?.pause();
} else {
startPoll();
document.querySelector("video")?.play();
}
});18navigator.onLine
true does not mean the API is reachable (captive portal, DNS fail).
- navigator.onLine
console.log(navigator.onLine); // true | false
if (!navigator.onLine) {
console.log("queue writes in IndexedDB until we reconnect");
}19online and offline events
Still verify with a real fetch — the event is not a heartbeat.
- online and offline events
window.addEventListener("offline", () => document.body.classList.add("offline"));
window.addEventListener("online", async () => {
document.body.classList.remove("offline");
try {
await fetch("/api/health", { cache: "no-store" });
} catch {
console.log("online flag lied; still unreachable");
}
});20Pick the right API
ResizeObserver — did this node change size? MutationObserver — did the DOM change? Worker — heavy CPU off the main thread. rAF — visual frames. Idle — leftover time. matchMedia — CSS queries. Visibility / onLine — tab and network hints.
- Pick the right API
const when = {
lazyImage: "IntersectionObserver",
sidebarWidth: "ResizeObserver",
thirdPartyDom: "MutationObserver",
fib40: "Worker + postMessage",
tween: "requestAnimationFrame",
analytics: "requestIdleCallback",
breakpoint: "matchMedia",
pauseVideo: "visibilitychange",
syncQueue: "online / navigator.onLine",
};
console.log(when.lazyImage);Array Methods
38 items01at()
Negative indexes count from the end.
const arr = [10, 20, 30, 40];
console.log(arr.at(1)); // 20
console.log(arr.at(-1)); // 4002concat()
const a1 = [1, 2],
a2 = [3, 4];
console.log(a1.concat(a2)); // [1, 2, 3, 4]03copyWithin()
const arr1 = [1, 2, 3, 4, 5];
console.log(arr1.copyWithin(0, 3)); // [4, 5, 3, 4, 5]04entries()
for (const [i, v] of ["a", "b"].entries()) {
console.log(i, v); // 0 "a", 1 "b"
}05every()
console.log([2, 4, 6].every((n) => n % 2 === 0)); // true06fill()
const arr2 = [1, 2, 3, 4];
console.log(arr2.fill(0, 1, 3)); // [1, 0, 0, 4]07filter()
console.log([10, 20, 30].filter((n) => n > 15)); // [20, 30]08find()
console.log([5, 12, 8].find((n) => n > 10)); // 1209findIndex()
console.log([5, 12, 8].findIndex((n) => n > 10)); // 110findLast()
console.log([5, 12, 8].findLast((n) => n > 10)); // 12
11findLastIndex()
console.log([5, 12, 50].findLastIndex((n) => n > 10)); // 2
12flat()
console.log([1, [2, [3]]].flat(2)); // [1, 2, 3]13flatMap()
console.log([1, 2, 3].flatMap((n) => [n, n * 2])); // [1, 2, 2, 4, 3, 6]14forEach()
[1, 2, 3].forEach((n) => console.log(n * 2)); // 2, 4, 615includes()
console.log([1, 2, 3].includes(2)); // true16indexOf()
console.log(["a", "b", "a"].indexOf("a")); // 017lastIndexOf()
console.log(["a", "b", "a"].lastIndexOf("a")); // 218join()
console.log(["a", "b", "c"].join("-")); // "a-b-c"19keys()
console.log([...["a", "b"].keys()]); // [0, 1]20map()
console.log([1, 2, 3].map((n) => n * 2)); // [2, 4, 6]21pop()
const arr3 = [1, 2, 3];
console.log(arr3.pop()); // 3
console.log(arr3); // [1, 2]22push()
const arr4 = [1];
console.log(arr4.push(2, 3)); // 3
console.log(arr4); // [1, 2, 3]23reduce()
console.log([1, 2, 3].reduce((acc, val) => acc + val, 0)); // 624reduceRight()
console.log(["a", "b", "c"].reduceRight((acc, val) => acc + val)); // "cba"25reverse()
const arr5 = [1, 2, 3];
arr5.reverse();
console.log(arr5); // [3, 2, 1]26shift()
const arr6 = [1, 2, 3];
console.log(arr6.shift()); // 1
console.log(arr6); // [2, 3]27unshift()
console.log(arr6.unshift(0)); // 3
console.log(arr6); // [0, 2, 3]28slice()
console.log([1, 2, 3, 4].slice(1, 3)); // [2, 3]29splice()
<- changes original array
const arr7 = ["a", "b", "c", "d"];
arr7.splice(1, 2, "x"); // splice(start, how many items to remove, with what to change?)
console.log(arr7); // ["a", "x", "d"]30some()
console.log([1, 2, 3].some((n) => n > 2)); // true31sort()
const arr8 = [40, 1, 5];
arr8.sort((a, b) => a - b);
console.log(arr8); // [1, 5, 40]32toLocaleString()
console.log([1000, new Date("2020-01-01")].toLocaleString("en-US"));
// "1,000, 1/1/2020, 12:00:00 AM"33toString()
console.log([1, 2, 3].toString()); // "1,2,3"34values()
for (const v of ["a", "b"].values()) {
console.log(v); // "a", "b"
}35Array.isArray() (static)
console.log(Array.isArray([1, 2])); // true
console.log(Array.isArray("hi")); // false36Array.from() (static)
console.log(Array.from("123")); // ["1", "2", "3"]37Array.of() (static)
console.log(Array.of(1, 2, 3)); // [1, 2, 3]
//
// Multidimensional Arrays in JavaScript
// Definition
// A multidimensional array is an array that contains other arrays as its elements.
const arr22 = [
[1, 2, 3],
[4, 5, 6],
];
console.log(arr22[0][1]); // output: 238interview
| Method | Creates New Array | Updates Existing Array | Returns |
|---|---|---|---|
| forEach | ❌ No | ✅ Yes (if you modify it) | undefined |
| map | ✅ Yes | ❌ No | New array |
| filter | ✅ Yes | ❌ No | New array (filtered) |
| reduce | ❌ No | ❌ No | Single value (any type) |
Object Methods
25 items01Object.assign()
const target = { a: 1 };
const source = { b: 2 };
console.log(Object.assign(target, source)); // { a: 1, b: 2 }02Object.create()
const proto = { greet: () => "hi" };
const obj = Object.create(proto);
console.log(obj.greet()); // "hi"03Object.defineProperty()
const obj1 = {};
Object.defineProperty(obj1, "x", { value: 42, writable: false });
console.log(obj1.x); // 4204Object.defineProperties()
const obj2 = {};
Object.defineProperties(obj2, {
a: { value: 1 },
b: { value: 2, writable: true },
});
console.log(obj2); // { a: 1, b: 2 }05Object.entries()
console.log(Object.entries({ x: 1, y: 2 })); // [["x", 1], ["y", 2]]06Object.fromEntries()
console.log(
Object.fromEntries([
["x", 1],
["y", 2],
])
); // { x: 1, y: 2 }07Object.freeze()
const frozen = Object.freeze({ a: 1 });
frozen.a = 2;
console.log(frozen.a); // 108Object.isFrozen()
console.log(Object.isFrozen(frozen)); // true09Object.seal()
const sealed = Object.seal({ a: 1 });
sealed.a = 2;
console.log(sealed); // { a: 2 }10Object.isSealed()
console.log(Object.isSealed(sealed)); // true11Object.preventExtensions()
const o1 = { a: 1 };
Object.preventExtensions(o1);
o1.b = 2;
console.log(o1); // { a: 1 }12Object.isExtensible()
console.log(Object.isExtensible(o1)); // false13Object.getOwnPropertyDescriptor()
const obj3 = { x: 10 };
console.log(Object.getOwnPropertyDescriptor(obj3, "x"));
// { value: 10, writable: true, enumerable: true, configurable: true }14Object.getOwnPropertyDescriptors()
console.log(Object.getOwnPropertyDescriptors(obj3));15Object.getOwnPropertyNames()
console.log(Object.getOwnPropertyNames({ a: 1, b: 2 })); // ["a", "b"]16Object.getOwnPropertySymbols()
const sym = Symbol("id");
const obj4 = { [sym]: 123 };
console.log(Object.getOwnPropertySymbols(obj4)); // [ Symbol(id) ]17Object.getPrototypeOf()
console.log(Object.getPrototypeOf([]) === Array.prototype); // true18Object.setPrototypeOf()
const animal = { eats: true };
const rabbit = {};
Object.setPrototypeOf(rabbit, animal);
console.log(rabbit.eats); // true19Object.hasOwn()
const obj5 = { a: 1 };
console.log(Object.hasOwn(obj5, "a")); // true
console.log(Object.hasOwn(obj5, "b")); // false20Object.keys()
console.log(Object.keys({ a: 1, b: 2 })); // ["a", "b"]21Object.values()
console.log(Object.values({ a: 1, b: 2 })); // [1, 2]22Object.is()
console.log(Object.is(NaN, NaN)); // true
console.log(Object.is(0, -0)); // false23Object.groupBy()
const arr = [1, 2, 3, 4, 5];
// console.log(Object.groupBy(arr, (n) => (n % 2 === 0 ? "even" : "odd")));
// { odd: [1, 3, 5], even: [2, 4] }
// ****************new examples******************************************************************
const obj = {
name: "John",
age: 30,
city: "Pune",
};
// 1
// console.log(Object.keys(obj).length ) // 3
// 2
// for (const key in obj) {
// console.log(key, obj[key]);
// }
// or
// Object.keys(obj).forEach(key => {
// console.log(key, obj[key]);
// });
// output
// name John
// age 30
// city Pune
Object.keys(obj); // ['name', 'age', 'city']
Object.values(obj); // ['John', 30, 'Pune']
Object.entries(obj); // [['name', 'John'], ['age', 30], ['city', 'Pune']]
// Check if Key Exists24'name' in obj; // ✅ true
25obj.hasOwnProperty('city'); // ✅ true
Object.freeze(obj);
obj.name = "Doe"; // ignored or error in strict mode
const scores = {
John: 90,
Alice: 82,
Bob: 40,
Dave: 65,
};
const passed = Object.entries(scores)
.filter(([name, score]) => score >= 60)
.reduce((acc, [name, score]) => {
acc[name] = score;
return acc;
}, {});
console.log(passed); // { John: 90, Alice: 82, Dave: 65 }
const Scores = {
John: 90,
Alice: 82,
Bob: 40,
Dave: 65,
};
const sum = Object.entries(Scores)
.map(([key, val]) => val)
.reduce((acc, val) => acc + val, 0);
console.log(sum);String Methods
35 items01Example
const str = "Hello";02at()
console.log(str.length); // 5
console.log(str.at(1)); // "e"
console.log(str.at(-1)); // "o"03charAt()
console.log(str.charAt(0)); // "H"04charCodeAt()
console.log(str.charCodeAt(0)); // 7205codePointAt()
console.log("😊".codePointAt(0)); // 12852206concat()
console.log("Hello".concat(" ", "World")); // "Hello World"07includes()
console.log(str.includes("Hell")); // true
console.log(str.includes("hey")); // false08endsWith()
console.log(str.endsWith("lo")); // true
console.log(str.endsWith("He")); // false09startsWith()
console.log(str.startsWith("He")); // true10indexOf()
console.log(str.indexOf("l")); // 211lastIndexOf()
console.log(str.lastIndexOf("l")); // 312match()
console.log("cat bat mat".match(/at/g)); // ["at", "at", "at"]13matchAll()
for (const m of "test1test2".matchAll(/test\d/g)) {
console.log(m[0]); // "test1", "test2"
}14padStart()
console.log("5".padStart(3, "0")); // "005"15padEnd()
console.log("5".padEnd(3, "0")); // "500"16repeat()
console.log("ha".repeat(3)); // "hahaha"17replace()
console.log("Hello World".replace("World", "JS")); // "Hello JS"18replaceAll()
console.log("a-b-c".replaceAll("-", "|")); // "a|b|c"19search()
console.log("hello".search(/l/)); // 220slice()
console.log("Hello".slice(1, 4)); // "ell"21substring()
console.log("Hello".substring(1, 4)); // "ell"22substr()
console.log("Hello".substr(1, 3)); // "ell"23split()
console.log("a,b,c".split(",")); // ["a", "b", "c"]24toLowerCase()
console.log("HELLO".toLowerCase()); // "hello"25toUpperCase()
console.log("hello".toUpperCase()); // "HELLO"26trim()
console.log(" hi ".trim()); // "hi"27trimStart()
console.log(" hi".trimStart()); // "hi"28trimEnd()
console.log("hi ".trimEnd()); // "hi"29valueOf()
console.log(new String("Hello").valueOf()); // "Hello"30toString()
console.log((123).toString()); // "123"31localeCompare()
Returns -1 (smaller), 0 (equal), 1 (greater).
console.log("a".localeCompare("b")); // -132normalize()
console.log("\u00F1".normalize("NFD")); // "ñ"33fromCharCode()
console.log(String.fromCharCode(72, 101, 108, 108, 111)); // "Hello"34fromCodePoint()
console.log(String.fromCodePoint(128522)); // "😊"35raw()
console.log(String.raw`Hello\nWorld`); // "Hello\nWorld"