Language fundamentals

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 items
01How JavaScript runs: engine, runtime, and call stack
JavaScript is single-threaded. Your code runs on a call stack inside an engine (V8, SpiderMonkey); the runtime adds APIs like setTimeout and fetch that the engine does not provide on its own.
When you run a script, the engine parses source into an AST, compiles it (often JIT), and executes it instruction by instruction. Each function call pushes a new execution context (frame) onto the call stack. When a function returns, its frame is popped. If the stack grows without bound — for example, infinite recursion — you get RangeError: Maximum call stack size exceeded.
javascript
function a() {
  console.log("a start");
  b();
  console.log("a end");
}

function b() {
  console.log("b");
}

a();
// Output order: a start → b → a end

The 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.

Tip: Open DevTools → Sources → add a breakpoint and inspect the Call Stack panel while stepping through nested function calls. Seeing frames appear and disappear makes the model concrete.
Try it: Write three nested functions that log messages, call the outermost one, and sketch the stack state after each log line on paper before running the code.
02Execution context, hoisting, and the temporal dead zone
Before any line runs, JavaScript creates a global execution context and, for each function call, a new local context. 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.
Each context has two phases: creation (allocate variables, set up scope chain, determine 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.
javascript
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.

Tip: Prefer let and const by default. Use const unless you need to reassign the binding. This avoids hoisting surprises and makes intent clearer.
Try it: Predict the output of a snippet that mixes 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
JavaScript resolves variable names by walking outward through nested scopes at the point where a function was written, not where it is called. Inner functions retain access to outer bindings even after the outer function returns.
Scope is established by blocks ({} 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.
javascript
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 closure

This 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).

Tip: Draw scope boxes on paper: global → function → block. Arrow a variable lookup from inner to outer until you find the binding.
Try it: Write a counter factory 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.
Strict mode fixes silent mistakes: duplicate parameter names, octal literals, delete of non-configurable properties, and this defaulting to undefined in plain functions instead of the global object.
javascript
"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.

javascript
// 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));
Tip: Treat strict mode + modules as the modern baseline. Avoid relying on implicit globals or this-as-window behavior.
Try it: Create two files with ES module imports in a small Vite or native type="module" HTML setup. Confirm top-level variables are not on window.

Types & coercion

4 items
05Primitives vs objects: typeof and value categories
JavaScript has seven primitive types (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.
javascript
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.

javascript
let a = { n: 1 };
let b = a;
b.n = 2;
console.log(a.n); // 2 — same object
Tip: Use Array.isArray(x), x === null, or Object.prototype.toString.call(x) when you need precise type checks beyond typeof.
Try it: Write a function describe(value) that returns a human-readable type string distinguishing null, arrays, plain objects, and primitives.
06Truthy, falsy, and explicit coercion
In boolean contexts, values coerce to true or false. Falsy values are false, 0, -0, 0n, "", null, undefined, and NaN. Everything else is truthy — including [], {}, and "0".
Coercion happens in if, while, !, &&, ||, and the ternary operator. Explicit conversion uses Boolean(), !!, Number(), String(), or BigInt().
javascript
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.

javascript
0 == false;   // true (coercion)
0 === false;  // false
null == undefined; // true
null === undefined; // false
Tip: Use === and !== by default. When accepting user input, coerce explicitly at boundaries (forms, APIs) rather than relying on implicit rules deep in logic.
Try it: Build a 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
All numbers are IEEE 754 double-precision floats. NaN is not equal to anything including itself; use Number.isNaN. Decimal math can surprise you — use rounding strategies or integers (cents) for money.
javascript
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 lost

parseInt("42px", 10) parses leading digits; Number("42px") yields NaN. Always pass radix 10 to parseInt unless you intentionally parse octal/hex.

Tip: For currency, store amounts as integer cents or use a decimal library. For comparisons, consider Number.EPSILON or Math.abs(a - b) < epsilon for floats.
Try it: Write 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.
javascript
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:

javascript
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]));
}
Tip: React's dependency arrays and memoization rely on reference equality for objects. Create new object references only when data actually changes.
Try it: Implement 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 items
09Function declarations, expressions, and arrow functions
Declarations are hoisted and named; expressions bind a function to a variable; arrow functions lexically capture this and cannot be used as constructors. Choose based on hoisting needs, this behavior, and readability.
javascript
// 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.

Tip: Use arrows for callbacks and short expressions; use declarations for top-level named utilities; use method shorthand inside objects and classes.
Try it: Refactor a 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
Default parameters apply when the argument is undefined. Rest collects remaining arguments into an array; spread expands iterables into individual elements. Both are essential for flexible APIs.
javascript
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 win

Rest 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.

Tip: Use rest instead of arguments in modern code — it's real array-like and works in arrow functions.
Try it: Write 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
A closure is a function plus the lexical environment it was created in. Closures enable data privacy, partial application, and callbacks that remember context — the backbone of many JS patterns.
javascript
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 exposed

Closures in loops were historically tricky with var:

javascript
for (let i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 0); // 0, 1, 2 — new binding per iteration
}
Tip: Closures retain references, not copies, to outer variables (unless you copy primitives into a new let in each iteration). Watch memory: long-lived callbacks closing over large objects can prevent garbage collection.
Try it: Implement a once(fn) function that runs fn only on the first call and returns the same result thereafter.
12Higher-order functions: map, filter, reduce
Functions are first-class values — they can be passed as arguments and returned. map, filter, and reduce express data transformations declaratively and chain cleanly.
javascript
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.5

reduce is the most general — it can implement map and filter. Always provide an initial accumulator when the type matters (numbers, objects, arrays).

javascript
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 }
Tip: Prefer these over manual for loops when transforming collections — intent is clearer. For very hot paths or early break, a for...of loop may still be appropriate.
Try it: Given an array of transaction { type: "credit"|"debit", amount }, compute net balance using a single reduce.
13IIFE, recursion, and call stack discipline
An IIFE (Immediately Invoked Function Expression) runs once to create a private scope. Recursion solves problems by self-similar subproblems but must have a base case and progress toward it to avoid stack overflow.
javascript
// 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); // 120

Tail call optimization is not guaranteed in all JS engines; deep recursion may fail. Convert to iteration when depth is unbounded:

javascript
function factorialIter(n) {
  let result = 1;
  for (let i = 2; i <= n; i++) result *= i;
  return result;
}
Tip: For tree/graph walks, consider an explicit stack (iterative DFS) or queue (BFS) instead of naive recursion on large structures.
Try it: Write recursive and iterative versions of sumNested(array) where arrays may contain numbers or nested arrays, e.g. [1, [2, [3]], 4] → 10.

this & prototypes

3 items
14The 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.
javascript
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 this

bind returns a new function with permanently bound this:

javascript
const boundGreet = user.greet.bind(user);
boundGreet(); // "Ada"
Tip: Extracting methods (const fn = obj.method) loses implicit binding — use bind, wrap in arrow inside the method, or call as obj.method().
Try it: Create an object with two methods that call each other via this. Break it by destructuring one method, then fix with bind.
15Prototype chain and object creation patterns
Objects delegate property lookups to their [[Prototype]] (exposed as __proto__ or via Object.getPrototypeOf). Functions have a prototype property used when invoked with new. Classes are syntactic sugar over prototypes.
javascript
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.prototype

Class syntax:

javascript
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.

Tip: Prefer class for readability today, but understand prototypes for debugging (instanceof, library code, and interview questions).
Try it: Build the same Counter with (a) a factory + closures, (b) constructor + prototype, and (c) class. List trade-offs for each.
16Inheritance, super, and composition over inheritance
Prototypal inheritance links child prototypes to parent prototypes. extends and super wire this up in classes. Favor composition (has-a) when behavior mixing is simpler than deep inheritance trees.
javascript
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:

javascript
const canFly = {
  fly() { return `${this.name} flies`; },
};

function createBird(name) {
  return Object.assign({ name }, canFly);
}
Tip: Deep inheritance hierarchies become fragile. Mix small behaviors (objects/functions) into factories or classes instead of stacking extends many levels.
Try it: Model 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 items
17Destructuring and shorthand object syntax
Destructuring unpacks arrays and objects into variables. Combined with default values and rest patterns, it makes function parameters and API responses concise to work with.
javascript
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 property

Swap without a temp variable:

javascript
let a = 1, b = 2;
[a, b] = [b, a];

Nested destructuring works but keep it readable — extract in steps for deeply nested API JSON.

Tip: In function signatures, destructure options objects with defaults instead of positional parameters when there are many optional settings.
Try it: Write 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
ES modules are statically analyzable, run in strict mode, and support named exports, default exports, and re-exports. Imported bindings are live — if the exporting module updates a let, importers see the new value.
javascript
// 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:

javascript
const module = await import("./heavy-chart.js");
module.renderChart(data);
Tip: Prefer named exports for utilities (better tree-shaking and explicit APIs). Reserve default export for the primary thing a file provides.
Try it: Split a tiny app into three modules: 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
An iterable implements Symbol.iterator returning an iterator. An iterator has next() returning { value, done }. for...of, spread, and destructuring consume iterables.
javascript
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:

javascript
function* ids() {
  let id = 1;
  while (true) yield id++;
}
const gen = ids();
gen.next(); // { value: 1, done: false }
Tip: Custom iterables make collection-like objects feel native. Generators shine for lazy sequences and paginated data streams.
Try it: Implement an iterable 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.
javascript
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;
}
Tip: Use 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.
Try it: Deduplicate an array of user objects by id using a Map, preserving first occurrence order.

Async: promises, async/await, event loop

5 items
21Synchronous vs asynchronous code and the event loop
JavaScript runs one call stack thread. Async work is delegated to the runtime (timers, network, I/O). When async work completes, callbacks join task queues; the event loop picks them when the stack is empty.
javascript
console.log("1");

setTimeout(() => console.log("2"), 0);

Promise.resolve().then(() => console.log("3"));

console.log("4");
// Order: 1, 4, 3, 2

Microtasks (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:

  1. Run synchronous code until the stack clears.
  2. Drain all microtasks.
  3. Take one macrotask (e.g. timer callback).
  4. Repeat.
Tip: Long synchronous loops block rendering and input. Break heavy work into chunks (requestAnimationFrame, setTimeout(0), or Web Workers).
Try it: Predict output for a snippet mixing setTimeout, promises, and synchronous logs. Verify in Node and the browser — order should match for this example.
22Callbacks, callback hell, and error-first conventions
Callbacks are functions passed to run later. Node popularized error-first callbacks (err, data) => {}. Deep nesting ("callback hell") hurts readability — promises and async/await improve structure, but callbacks remain at the runtime boundary.
javascript
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:

javascript
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);
Tip: When wrapping callback APIs, promisify once (util.promisify in Node or a small helper) and use async/await everywhere else.
Try it: Wrap a fake readFile(path, cb) callback API in a readFileAsync promise and load two files sequentially with async/await.
23Promises: states, chaining, and combinators
A promise is pending, fulfilled, or rejected — transitioning once. .then handles fulfillment, .catch handles rejection, .finally runs either way. Promise.all, race, allSettled, and any coordinate multiple async operations.
javascript
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:

javascript
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.

Tip: Always return promises from .then handlers when starting async work — forgetting return breaks chains silently.
Try it: Fetch three fake delays with 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.
javascript
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:

javascript
// 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:

javascript
// config.js
export const settings = await fetch("/api/settings").then((r) => r.json());
Tip: Await inside loops runs sequentially. Use Promise.all(items.map(async ...)) when operations are independent.
Try it: Write 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
Understanding queue ordering explains subtle bugs: DOM updates, promise chains, and setTimeout(0) interleaving. Async debugging means reading stack traces, logging with labels, and breaking on uncaught promise rejections.
javascript
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 end

await schedules continuation as a microtask. Nested async functions add layers but still respect microtask draining before timers.

Debugging tips:

javascript
// 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);
});
Tip: If UI doesn't update when expected, check whether you're mutating state before an async gap and reading stale closure values — log right before and after await.
Try it: Create a function that logs three steps using await Promise.resolve() between each and diagram which logs are sync vs microtask.

DOM & events

3 items
26Selecting and updating the DOM
The DOM is a tree of nodes representing HTML. Use querySelector / querySelectorAll for selection, textContent / innerHTML (carefully) for content, and classList / dataset for attributes and state.
javascript
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.

Tip: Cache DOM references outside hot loops, but don't over-cache — if the DOM is recreated, stale references point nowhere.
Try it: Build a tiny todo list renderer: given { id, text, done }[], clear #list and render <li> elements with a done class toggle — no framework.
27Events: bubbling, delegation, and preventDefault
Events flow from target → ancestors (bubble phase) unless stopped. Event delegation attaches one listener on a parent and uses event.target to handle children — ideal for dynamic lists. preventDefault stops default browser behavior; stopPropagation stops further propagation.
javascript
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.

Tip: Delegate from stable ancestors (document, #app) for lists that re-render. Compare event.target (deepest element) vs event.currentTarget (element with listener).
Try it: Render a button list dynamically. One delegated click handler on #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.
javascript
// 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:

javascript
const res = await fetch("/api/users");
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const users = await res.json();
Tip: Prefer rAF over setInterval for visual updates — it pauses in background tabs and aligns with paint.
Try it: Animate a div moving across the screen with requestAnimationFrame, stopping after 2 seconds. Log frame count.

Errors & debugging

2 items
29Throwing, catching, and custom errors
Use 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.
javascript
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.

Tip: When rethrowing, preserve the original error as cause (ES2022): throw new Error("Failed to save", { cause: err }).
Try it: Build assert(condition, message) that throws an AssertionError subclass. Use it in a small validator for email format.
30Debugging workflow: breakpoints, logging, and DevTools
Effective debugging combines reproducible steps, strategic console methods, breakpoints, and network inspection — not random console.log everywhere.
javascript
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 === 42

Workflow:

  1. Reproduce reliably with minimal input.
  2. Form a hypothesis (wrong value, timing, scope).
  3. Inspect with breakpoint or targeted log.
  4. 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.

Tip: Use debugger; statement to pause when DevTools is open — faster than hunting line numbers during active investigation.
Try it: Take a buggy function that returns 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 items
31Debounce and throttle
Debounce delays execution until input stops for a wait period — ideal for search-as-you-type. Throttle runs at most once per interval — ideal for scroll/resize handlers. Both reduce expensive work.
javascript
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.

Tip: Always cancel debounced timers on component unmount (call a .cancel() if you add one) to avoid setState on unmounted components in React.
Try it: Wire debounce to an <input> and log API calls — confirm rapid typing produces one log after pause, not one per keystroke.
32Deep clone vs shallow copy
Shallow copy duplicates top-level properties; nested objects are still shared. Deep clone recursively copies the graph. structuredClone (modern) handles most cases; JSON round-trip loses types and skips functions, undefined, and cycles.
javascript
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:

javascript
JSON.parse(JSON.stringify({ d: new Date(), fn: () => {} }));
// Date becomes string, fn omitted
Tip: For immutable state updates (Redux, React), shallow copy plus targeted nested copy is often enough and faster than full deep clone.
Try it: Compare mutating nested data after {...obj}, structuredClone, and JSON clone. List which fields still alias the original.
33Currying and partial application
Currying transforms a function 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.
javascript
// 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"
Tip: Currying shines in functional pipelines; in everyday app code, default parameters and options objects are often clearer — use currying when you genuinely reuse specialized functions.
Try it: Curry a fetchWithBase(baseUrl)(path)(options) helper and create fetchApi preset with your API base URL.
34Memoization and caching function results
Memoization stores results of expensive pure functions keyed by arguments. It trades memory for speed when the same inputs repeat — classic for recursion (Fibonacci), parsing, and derived selectors.
javascript
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 cache

For 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.

Tip: Memoize only pure functions — cached results become wrong if the function depends on hidden mutable state or time.
Try it: Memoize a slow isPrime(n) and time isPrime(10007) twice with console.time. Add cache size logging.
35Piping, composition, and small utility design
Compose functions right-to-left; pipe left-to-right. Small, pure utilities composed together beat monolithic helpers. This closes the course by applying functions, closures, and immutability ideas to everyday code organization.
javascript
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, not processString).
  • Test edge cases: empty input, null, large data.
Tip: Lodash/fp and Ramda popularized these patterns; in modern apps, a few local pipe/compose lines often suffice without importing a library.
Try it: Build a 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 items
36Date model
JavaScript's 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.
javascript
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(); // 8

Getters 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.

Tip: For calendar dates with no time (birthdays, due dates), store "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().
Try it: Log 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.
The 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.
javascript
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.

Tip: Cache formatters at module scope. Creating new Intl.DateTimeFormat on every render is wasteful; the constructor does locale data lookup.
Try it: Format the same 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
Add time by working in milliseconds or UTC date parts; never add 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.
javascript
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.

Tip: If two users in different zones must agree on a meeting, store UTC (or a timezone-aware ISO string with offset) plus the intended IANA zone name ("Europe/Berlin"). Display each side in their own zone.
Try it: On a date near a DST transition (e.g. second Sunday in March, US), add one day with + 86400000 and with setDate(getDate() + 1). Compare getHours(). Write startOfUtcDay(date) that returns 00:00:00.000Z.
39When to use a library
Use the platform (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.
Native 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.
javascript
// 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.

Tip: Never 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.
Try it: List three date operations in an app you know. Mark each "native" or "library" using the table above. Implement the native ones; stub the library ones with a comment describing the API you would call.

Storage and persistence

2 items
40localStorage, 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.
All three are origin-scoped (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.
javascript
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).

Tip: 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.
Try it: Save a theme preference in 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
IndexedDB is the browser's structured, async database for large data (files, caches, offline apps). Storage is quota-limited per origin and can be evicted under pressure unless you persist it.
Unlike 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.
javascript
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.

Tip: Do not put IndexedDB writes on the critical path of a click without UI feedback. Transactions can take time; show a saving state. For a few KB of settings, localStorage is simpler.
Try it: Open a database, 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 items
42fetch 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.
javascript
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.

Tip: Treat AbortError as a normal control-flow outcome, not a toast-worthy failure, when the user cancelled or typed again.
Try it: Fetch a public JSON API with a 1 ms timeout and confirm you handle abort. Then wire a search input so each keystroke aborts the previous request.
43Retry, backoff, and FormData
Retry transient failures (network drop, 429, 503) with exponential backoff and jitter; do not retry 400 or 404. FormData builds multipart/form-data bodies for files without manual MIME boundaries.
A single 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.
javascript
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.

Tip: If you set Content-Type: multipart/form-data yourself, you omit the boundary and the server cannot parse the body. Let fetch + FormData set the header.
Try it: Write 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
CORS is a browser rule: a page on origin A may read a response from origin B only if B's headers allow it. The server opts in; the client cannot "disable CORS."
An origin is scheme + host + port (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.
javascript
// 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.

Tip: In local Next.js/Vite apps, proxy /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.
Try it: From your notes app origin, 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 items
45Groups and lookahead
Capture groups extract pieces; named groups keep them readable. Lookahead and lookbehind assert context without consuming characters — use them for passwords and delimiters, not for parsing HTML.
Parentheses create a capturing group; (?:...) 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.
javascript
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.

Tip: If you find yourself writing nested lookaheads to parse nested markup, stop. Use a parser or DOMParser. Regex is for regular languages — HTML is not one.
Try it: Write a named-group regex for 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
Regex can reject obviously bad input, but it is a poor single source of truth for email, URLs, or HTML — catastrophic backtracking and false confidence are the real risks.
A crafted string can make a naive regex take exponential time (ReDoS). Nested quantifiers like (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.
javascript
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).

Tip: If a regex is hard to name, it is doing too much. Split "shape check" from "business rule" (unique email, disposable domain, MX record).
Try it: Time /^(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 items
47IntersectionObserver and ResizeObserver
Observe visibility and size asynchronously instead of binding scroll and resize to layout-thrashing reads. IntersectionObserver tells you when an element enters a box; ResizeObserver tells you when its box changes.
Lazy-loaded images, infinite scroll, and "start the video when visible" used to mean 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).
javascript
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.

Tip: Do not read 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.
Try it: Lazy-load three images with IntersectionObserver. Attach ResizeObserver to a textarea and log width/height as the user resizes. Confirm observers stop after you call the cleanup function.
48Web Workers and requestIdleCallback
Web Workers run JS on another thread so heavy CPU work does not freeze the UI. requestIdleCallback schedules leftover main-thread work for idle periods — not a substitute for workers.
The main thread paints, handles input, and runs most of your app. A 50 ms JSON parse or markdown compile dropped into a click handler makes the page jank. A worker is a separate global (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.
javascript
// 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.

Tip: Cloning huge objects into a worker can cost as much as the work. Transfer ArrayBuffers (postMessage(buf, [buf])) or share a SharedArrayBuffer only with a clear memory model.
Try it: Move a naive Fibonacci or markdown word-count to a worker and compare UI smoothness vs running it on the main thread. Queue five idle tasks with requestIdleCallback and log deadline.timeRemaining().

Security basics

2 items
49XSS, sanitization, and CSP
Cross-site scripting (XSS) runs an attacker's JavaScript in your origin. Never assign untrusted strings to innerHTML; sanitize or use textContent, and lock down what can execute with Content-Security-Policy.
If you render 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.
javascript
function renderComment(el, userText) {
  el.textContent = userText; // safe: no HTML parse
}

function escapeHtml(s) {
  return s
    .replaceAll("&", "&amp;")
    .replaceAll("<", "&lt;")
    .replaceAll(">", "&gt;")
    .replaceAll('"', "&quot;")
    .replaceAll("'", "&#39;");
}

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.

Tip: Search the codebase for innerHTML, dangerouslySetInnerHTML, and eval. Each hit needs a justification and a sanitizer or a rewrite to textContent.
Try it: Put <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
Access tokens in 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.
JWT or opaque session IDs prove the user to your API. Where you put them is a trade-off between XSS and CSRF. 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.
javascript
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.

Tip: If a tutorial says "store the JWT in localStorage," treat it as a prototype, not a production pattern. Pair tokens with short expiry, rotation, and server-side revocation.
Try it: Sketch your app's auth: where the access token lives, where the refresh token lives, and what happens on XSS vs CSRF. Implement apiFetch against a mock that returns 401 once, then succeeds after bootstrapSession.

Data Types

4 items
01JavaScript is dynamically typed and weakly typed, meaning
JavaScript is dynamically typed and weakly typed, meaning: Variables don’t have fixed types

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
Primitive types are immutable and stored by value

ex. Number , BigInt , String , undefined , null , boolean , symbol

  1. Primitive Data Types
03Non-Primitive (Reference) Types
Stored by reference in memory

ex. object , array , functions

  1. Non-Primitive (Reference) Types
js
// Primitive vs Reference
04Copy behavior
  1. Copy behavior
js
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 items
01A variable is a named container that stores data in memory s
A variable is a named container that stores data in memory so it can be used and updated later
js
// | Keyword | Scope    | Reassign | Hoisted | Use Case  |
// | ------- | -------- | -------- | ------- | --------- |
02Notes
| var | Function | ✅ | Yes | ❌ Avoid |
03Notes
| let | Block | ✅ | No* | ✅ Default |
04Notes
| const | Block | ❌ | No* | ✅ Default |
js
// | Declaration | Hoisted | Initialized |
// | ----------- | ------- | ----------- |
05Notes
| var | ✅ | undefined |
06Notes
| let | ✅ | ❌ | if access before initialization gives ReferenceError
07Notes
| const | ✅ | ❌ | if access gives ReferenceError
js
{
  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 |
js
// 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 first

Math

2 items
01JavaScript Math Operators & Math Methods
JavaScript Math Operators & Math Methods
js
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
OperatorLong FormShort Form
+=x = x + yx += y
-=x = x - yx -= y
*=x = x * yx *= y
/=x = x / yx /= y
%=x = x % yx %= y
**=x = x ** yx **= y

Loops

9 items
01JavaScript Loops – All Types
JavaScript Loops – All Types
js
// A loop is used to run the same code repeatedly until a condition is met

// --------------------------------
02for loop
Used when number of iterations is known
  1. for loop
js
for (let i = 1; i <= 5; i++) {
  console.log(i); // output: 1 2 3 4 5
}

// --------------------------------
03while loop
Checks condition first, then runs code Used when iterations depend on condition
  1. while loop
js
let w = 1;
while (w <= 5) {
  console.log(w); // output: 1 2 3 4 5
  w++;
}

// --------------------------------
04do...while loop
Runs code at least once, then checks condition
  1. do...while loop
js
let d = 1;
do {
  console.log(d); // output: 1 2 3 4 5
  d++;
} while (d <= 5);

// --------------------------------
05for...in loop
Used to loop over object keys (indexes or properties)
  1. for...in loop
js
const obj = { name: "Alice", age: 25 };

for (let key in obj) {
  console.log(key, obj[key]);
  // output: name Alice
  //         age 25
}

// --------------------------------
06for...of loop
Used to loop over iterable values (arrays, strings)
  1. for...of loop
js
const arr = [10, 20, 30];

for (let value of arr) {
  console.log(value); // output: 10 20 30
}

// --------------------------------
07forEach loop (Array method)
Used to loop through array elements Cannot break or continue
  1. forEach loop (Array method)
js
arr.forEach((item) => {
  console.log(item); // output: 10 20 30
});

// --------------------------------
08break statement
Stops the loop completely
  1. break statement
js
for (let i = 1; i <= 5; i++) {
  if (i === 3) break;
  console.log(i); // output: 1 2
}

// --------------------------------
09continue statement
Skips current iteration
  1. continue statement
js
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 iteration

Hoisting

55 items
01Hoisting is JavaScript’s default behavior of moving declarat
Hoisting is JavaScript’s default behavior of moving declarations to the top of their scope before execution
02Declaration Type · Hoisted? · Initialized? · Can Use Before
Declaration TypeHoisted?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.DependsDepends❌ Usually No
Arrow FunctionDependsDepends❌ No
Class✅ Yes❌ No❌ No (TDZ)
03Variable Hoisting
var Hoisted to the top of its function or global scope - Initialized with undefined
  1. Variable Hoisting
js
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
📌 TDZ = time between entering scope and actual declaration
js
// ------------------------------------------------------------------------------------------
05Function Hoisting
  1. Function Hoisting
js
// 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?
Why?

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
Arrow Functions - Arrow functions behave like function expressions
js
hello(); //  ReferenceError

const hello = () => {
  console.log("Hello");
};
08Class Hoisting - Classes are hoisted but not initialized (like let / const)
  1. Class Hoisting - Classes are hoisted but not initialized (like let / const).
js
const user = new User(); //  ReferenceError

class User {
  constructor(name) {
    this.name = name;
  }
}
09ARROW FUNCTION vs FUNCTION DECLARATION All examples and defi
ARROW FUNCTION vs FUNCTION DECLARATION All examples and definitions in one file
10FUNCTION DECLARATION
  1. FUNCTION DECLARATION
  • Fully hoisted (can be used before definition)
  • Has its own this
  • Has its own arguments object
  • Can be used as a constructor (with new)
11Example
js
sayHello2(); // ✅ Works because function declarations are hoisted

function sayHello2() {
  console.log("Hello from function declaration");
}
12ARROW FUNCTION
  1. 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)
greet(); // ❌ ReferenceError (cannot access before initialization)
js
const greet = () => {
  console.log("Hello from arrow function");
};

greet(); // ✅ Works after declaration
14THIS BEHAVIOR (MOST IMPORTANT DIFFERENCE)
  1. THIS BEHAVIOR (MOST IMPORTANT DIFFERENCE)
15Function Declaration → this is dynamic
Function Declaration → this is dynamic
js
const 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
  1. THIS INSIDE CALLBACKS
17Example
js
function TimerWithFunction() {
  this.count = 0;

  setInterval(function () {
18❌ this is not TimerWithFunction
❌ this is not TimerWithFunction console.log(this.count); // undefined
js
}, 1000);
}

function TimerWithArrow() {
  this.count = 0;

  setInterval(() => {
19✅ arrow inherits this from TimerWithArrow
✅ arrow inherits this from TimerWithArrow
js
this.count++;
    console.log("Arrow timer:", this.count);
  }, 1000);
}

// Uncomment to test
// new TimerWithArrow();
20ARGUMENTS OBJECT
  1. ARGUMENTS OBJECT
21Example
js
function normalFunction() {
  console.log("Function arguments:", arguments);
}

normalFunction(1, 2, 3);
22Arrow functions do NOT have arguments
Arrow functions do NOT have arguments
js
const arrowFunction = () => {
23console.log(arguments); // ❌ ReferenceError
console.log(arguments); // ❌ ReferenceError
js
};

// Correct way with arrow function
const arrowWithRest = (...args) => {
  console.log("Arrow rest args:", args);
};

arrowWithRest(1, 2, 3);
24WHEN TO USE WHAT (SUMMARY)
WHEN 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 *--------------------------------------------------
Function *----------------------------------------------------------------------------------------------*
26FUNCTION DECLARATION
  1. FUNCTION DECLARATION
27function add(a, b) {
function add(a, b) { return a + b; }
28FUNCTION EXPRESSION
  1. FUNCTION EXPRESSION
29const add = function (a, b) {
const add = function (a, b) { return a + b; };
30ARROW FUNCTION
  1. ARROW FUNCTION
31const add = (a, b) => a + b;
const add = (a, b) => a + b;
32ANONYMOUS FUNCTION
  1. ANONYMOUS FUNCTION
33setTimeout(function () {
setTimeout(function () { console.log("Anonymous function"); }, 1000);
34NAMED FUNCTION EXPRESSION
  1. NAMED FUNCTION EXPRESSION
35const factorial = function fact(n) {
const factorial = function fact(n) { return n <= 1 ?

1 : n * fact(n - 1); };

36IMMEDIATELY INVOKED FUNCTION EXPRESSION (IIFE)
  1. IMMEDIATELY INVOKED FUNCTION EXPRESSION (IIFE)
37(function () {
(function () { console.log("IIFE function"); })();
38GENERATOR FUNCTION
  1. GENERATOR FUNCTION
39function* generatorExample() {
function* generatorExample() { yield 1; yield 2; }
40ASYNC FUNCTION
  1. ASYNC FUNCTION
41async function fetchData() {
async function fetchData() { const data = await fetch(url); }
42ASYNC ARROW FUNCTION
  1. ASYNC ARROW FUNCTION
43const fetchData = async () => {
const fetchData = async () => { const data = await fetch(url); };
44CALLBACK FUNCTION
  1. CALLBACK FUNCTION
45function callbackExample(cb) {
function callbackExample(cb) { cb(); }
46A function that takes a function as a argument and returns a
A function that takes a function as a argument and returns a new function as its result
  1. HIGHER-ORDER FUNCTION
47function higherOrder(fn) {
function higherOrder(fn) { return function () {}; }
48CONSTRUCTOR FUNCTION
  1. CONSTRUCTOR FUNCTION
49function Person(name) {
function Person(name) { this.name = name; }
50RECURSIVE FUNCTION
  1. RECURSIVE FUNCTION
51function factorial(n) {
function factorial(n) { return n <= 1 ?

1 : n * factorial(n - 1); }

52METHOD (OBJECT FUNCTION)
  1. METHOD (OBJECT FUNCTION)
53const obj = {
const obj = { greet() { console.log("Hello"); } };
54DEFAULT PARAMETER FUNCTION
  1. DEFAULT PARAMETER FUNCTION
55function greet(name = "Guest") {
function greet(name = "Guest") { console.log(name); }

Code Execution

16 items
01JAVASCRIPT RUNTIME DEMO
JAVASCRIPT RUNTIME DEMO

Concepts covered:

  • Call Stack
  • Synchronous code
  • Promises (Microtask Queue)
  • setTimeout (Macrotask / Callback Queue)
  • Event Loop
02Example
js
console.log("1. Script start");
03SYNC CODE (CALL STACK) Runs immediately, line by line
SYNC CODE (CALL STACK) Runs immediately, line by line
04Example
js
function syncFunction() {
  console.log("2. Inside sync function");
}

syncFunction();
05PROMISE (MICROTASK QUEUE) Microtasks run AFTER sync code but
PROMISE (MICROTASK QUEUE) Microtasks run AFTER sync code but BEFORE macrotasks
06Example
js
Promise.resolve().then(() => {
  console.log("4. Promise resolved (microtask)");
});
07SETTIMEOUT (MACROTASK QUEUE) Runs AFTER microtasks
SETTIMEOUT (MACROTASK QUEUE) Runs AFTER microtasks
08Example
js
setTimeout(() => {
  console.log("6. setTimeout callback (macrotask)");
}, 0);
09COMPLEX NESTED EXAMPLE
COMPLEX NESTED EXAMPLE
10Example
js
setTimeout(() => {
  console.log("7. setTimeout start");

  Promise.resolve().then(() => {
    console.log("8. Promise inside setTimeout");
  });

  console.log("9. setTimeout end");
}, 0);
11MORE PROMISES
MORE PROMISES
12Example
js
Promise.resolve().then(() => {
  console.log("5. Second promise");
});
13FINAL SYNC CODE
FINAL SYNC CODE
14Example
js
console.log("3. Script end");
15EXPECTED OUTPUT ORDER
EXPECTED OUTPUT ORDER
  1. Script start
  2. Inside sync function
  3. Script end
  4. promise
  5. Promise resolved (microtask)
  6. setTimeout callback (macrotask)
  7. setTimeout start
  8. setTimeout end
  9. Promise inside setTimeout
16RUNTIME EXPLANATION (MENTAL MODEL)
RUNTIME EXPLANATION (MENTAL MODEL)
  1. Execute all SYNC code (Call Stack)
  2. Execute all MICROTASKS (Promises)
  3. Execute ONE MACROTASK (setTimeout)
  4. After each macrotask, clear microtasks again
  5. Repeat (Event Loop)

BOM

1 item
01Browser Object Model (BOM)
Browser Object Model (BOM) Allows JS to interact with the browser (window)
js
// 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 items
01DOM stands for Document Object Model
DOM 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.

js
// 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 Methods
02document.getElementById()
Selects a single HTML element using its unique ID
  1. document.getElementById()
js
document.getElementById("idName");

// Returns:
// A single Element object, or null if not found.

const title = document.getElementById("main-title");
03document.getElementsByClassName()
Selects all elements that share a common class name
  1. document.getElementsByClassName()
js
document.getElementsByClassName("className");
// Returns:
// An HTMLCollection (live, array-like list of elements).

const cards = document.getElementsByClassName("card");
04document.getElementsByTagName()
Definition: Selects all elements with a given HTML tag name
  1. document.getElementsByTagName()
js
document.getElementsByTagName("tagName");

// Returns:
// An HTMLCollection.

const paragraphs = document.getElementsByTagName("p");
05document.querySelector()
Definition: Returns the first element that matches a given CSS selector
  1. document.querySelector()
js
// Returns:
// A single Element object, or null.

const firstCard = document.querySelector(".card");
const main = document.querySelector("#main");
06document.querySelectorAll()
Definition: Returns all elements that match a given CSS selector
  1. document.querySelectorAll()
js
// document.querySelectorAll("selector")
// Returns:
// A NodeList (static, array-like list of elements).

const allCards = document.querySelectorAll(".card");
07Document Object Model
Document Object Model
js
// The DOM is a tree-like JavaScript representation of your HTML created by the browser.
08<body> <h1>Hello</h1> <p>World</p> </body>
<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 items
01Event flow
Three phases: capturing (window → target), target, bubbling (target → window)

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.

  1. Event flow
js
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 bubble
02addEventListener options
Third argument: boolean (capture) or an options object

capture, once, passive, signal (AbortController). Default is bubble + not once.

  1. addEventListener options
js
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 phase
03Event delegation
One listener on a parent handles many children via event.target

Works for elements added later. Prefer closest() so clicks on inner nodes (span inside a button) still match. Check contains() if needed.

  1. Event delegation
js
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
Stops the browser's default action (navigate, submit, check a box)

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.

  1. preventDefault
js
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
stopPropagation: no further nodes in capture/bubble see this event

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.

  1. stopPropagation vs stopImmediatePropagation
js
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
{ once: true } auto-removes the listener after the first fire

Same as wrapping the handler and calling removeEventListener yourself. Useful for first-interaction, one-shot popovers, or init-on-click.

  1. once
js
button.addEventListener("click", () => console.log("only once"), { once: true });
07passive
Promises the handler will not call preventDefault

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.

  1. passive
js
window.addEventListener("touchstart", onTouch, { passive: true });
window.addEventListener(
  "wheel",
  (e) => {
    // e.preventDefault(); // ignored if passive: true
  },
  { passive: true },
);
08Custom events
CustomEvent carries a detail payload

Set bubbles/cancelable or it stays on the target only. composed: true crosses shadow DOM. dispatchEvent is synchronous — listeners run before the next line.

  1. Custom events
js
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 CustomEvent
09removeEventListener pitfalls
Must pass the same function reference AND the same capture flag

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.

  1. removeEventListener pitfalls
js
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 it
10Event object essentials
type, target (origin), currentTarget (the node whose listener is running), eventPhase (1 capture / 2 target / 3 bubble), timeStamp

Mouse: clientX/Y, button. Keyboard: key, code, repeat. Do not confuse target with currentTarget during delegation.

  1. Event object essentials
js
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
click, dblclick, input, change, submit, focus, blur (no bubble — use focusin / focusout if you need delegation), keydown, pointerdown, scroll (does not bubble; listen on the scroller), resize on window
  1. Common listener types
js
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 items
01Constructing a Date
new Date() captures "now" as a millisecond instant since the Unix epoch

The object stores UTC internally; console output uses the local timezone. Calling it as a function (Date()) returns a string, not a Date.

  1. Constructing a Date
js
const now = new Date();
console.log(now instanceof Date);
console.log(typeof Date());
console.log(now.getTime());
02From Unix milliseconds
new Date(ms) treats the argument as milliseconds since 1970-01-01T00:00:00.000Z

Negative values are instants before the epoch. Passing a single number is never "year" — use the multi-argument form for that.

  1. From Unix milliseconds
js
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
new Date(y, monthIndex, day, h, min, s, ms) uses the local timezone

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.

  1. Component constructor is local
js
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
Date.UTC(y, monthIndex, ...) returns a millisecond timestamp in UTC

Wrap it with new Date(...) to get a Date for that instant. Component order matches the local constructor, including 0-indexed months.

  1. Date.UTC and the Date wrapper
js
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
new Date(string) and Date.parse(string) share the same parser

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.

  1. Parsing date strings
js
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
Date.parse returns a number (ms) or NaN — it never throws

Slash dates, month names, and missing timezones differ across engines. Prefer an explicit ISO string with Z, or build from numeric components.

  1. Date.parse pitfalls
js
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
A date-only ISO string ("YYYY-MM-DD") is parsed as UTC midnight

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.

  1. ISO date-only strings are UTC
js
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
"YYYY-MM-DDTHH:mm:ss" with no Z or offset is treated as local time

The same clock reading therefore maps to different instants per machine TZ. Always include Z or an offset when the instant must be unambiguous.

  1. ISO datetime without Z is local
js
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
Months are 0–11 (January = 0, December = 11)

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.

  1. Zero-indexed months
js
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
Failed parsing produces an Invalid Date object, not an exception

Its primitive value is NaN; Number(invalid) is NaN; String(invalid) is "Invalid Date". Most getters return NaN; toISOString() throws RangeError.

  1. Invalid Dates
js
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.getTime()) is the reliable check (or Number.isNaN(+date))

Number.isNaN(date) is always false because date is an object. Guard before formatting, comparing, or sending a Date over the wire.

  1. Detecting invalid Dates
js
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
getFullYear, getMonth, getDate, getHours, getMinutes, getSeconds, getMilliseconds and getDay read the calendar/clock in the host timezone

getYear() is deprecated (years since 1900) — always use getFullYear().

  1. Local getters
js
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
The UTC* getters read the same instant in UTC, independent of the host TZ

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.

  1. UTC getters
js
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
setFullYear / setMonth / setDate / setHours / ..

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.

  1. Local setters and overflow
js
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
setUTCFullYear, setUTCMonth, setUTCDate, setUTCHours, and friends mutate using UTC fields

Overflow rules are the same as the local setters. Prefer UTC setters when the Date represents a civil date stored at UTC midnight.

  1. UTC setters
js
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
getTime() and valueOf() both return epoch milliseconds; +date is the same via ToPrimitive

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.

  1. getTime, valueOf, and Date.now
js
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
Unix time is usually seconds; JavaScript Date is always 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.

  1. Unix timestamps: seconds vs milliseconds
js
const unixSeconds = 1773532800;
const fromUnix = new Date(unixSeconds * 1000);
console.log(fromUnix.toISOString());
console.log(Math.floor(fromUnix.getTime() / 1000) === unixSeconds);
18toISOString
toISOString() always prints UTC with a trailing Z and millisecond precision

It is the right default for logs, JSON, and API payloads. Invalid Date causes a RangeError — validate first.

  1. toISOString
js
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
JSON.stringify calls toJSON() on Date, which delegates to toISOString()

Nested dates therefore survive a round-trip as ISO strings, not Date objects. After JSON.parse you must new Date(string) yourself.

  1. toJSON for APIs
js
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
toString / toDateString / toTimeString use the host locale and timezone

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.

  1. Locale and UTC string methods
js
const shown = new Date("2026-03-15T12:00:00.000Z");
console.log(shown.toDateString());
console.log(shown.toTimeString());
console.log(shown.toUTCString());
21Comparing Dates
< > <= >= coerce Dates to milliseconds, so they compare instants correctly

== and === compare object identity, so two equal instants are not ===. Prefer dateA.getTime() === dateB.getTime() for equality.

  1. Comparing Dates
js
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
sort mutates; subtract getTime() values for a numeric comparator

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.

  1. Sorting Dates
js
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
Every setter mutates the same object; sharing a Date across UI state is a footgun

Clone with new Date(original) or new Date(original.getTime()). structuredClone(date) also works and keeps a real Date.

  1. Dates are mutable — clone first
js
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
Instant arithmetic is just integer math on getTime()

Adding 24 hours of milliseconds is "add 24 hours", not "add one calendar day". Across DST that distinction matters — see the DST cards.

  1. Adding and subtracting milliseconds
js
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
setDate(getDate() + n) walks calendar days in the local zone and handles month/year rollover

Use setUTCDate(getUTCDate() + n) when the Date is a UTC civil date. Always clone first so the source instant stays put.

  1. Calendar-day arithmetic
js
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
Subtracting Dates (or their getTime()) yields the signed millisecond gap

Positive means the right operand is earlier when you write later - earlier. Math.abs if you only care about duration.

  1. Diff in milliseconds
js
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
Divide the ms delta by the unit size; floor toward zero or use trunc for signed diffs

This counts elapsed 24-hour periods, not "calendar midnights crossed". For calendar-day difference, compare UTC (or local) Y/M/D fields instead.

  1. Diff in days, hours, minutes
js
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
setHours(0, 0, 0, 0) snaps to local midnight; setHours(23, 59, 59, 999) is the last ms

These are local-civil, so the UTC ISO string will shift with the host offset. For a UTC day, use setUTCHours instead.

  1. Start and end of a local day
js
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
A year is a leap year if divisible by 4, except centuries not divisible by 400

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.

  1. Leap years
js
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
Build YYYY-MM-DD yourself from UTC (or local) getters plus String#padStart

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.

  1. Formatting without libraries
js
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
Intl.DateTimeFormat(locale, options) is the built-in way to format for humans

Default options are locale-sensitive; pass dateStyle/timeStyle or field options. format() returns a string; reuse one formatter when rendering lists.

  1. Intl.DateTimeFormat
js
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
The timeZone option formats the same instant in any IANA zone

This does not convert or mutate the Date; it only changes the printed fields. Invalid zone names throw RangeError at formatter construction.

  1. Formatting in a specific timezone
js
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
formatToParts returns [{ type, value }, ...] so you can style day vs month separately

Types include year, month, day, weekday, hour, minute, dayPeriod, timeZoneName, literal. Prefer this over regex-splitting format() output.

  1. formatToParts
js
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
RelativeTimeFormat(locale, { numeric, style }) formats a signed unit count

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".

  1. Intl.RelativeTimeFormat
js
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
getTimezoneOffset() is minutes to add to local time to get UTC (local + offset = UTC)

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.

  1. getTimezoneOffset
js
const offsetSample = new Date("2026-01-15T12:00:00Z");
const minutes = offsetSample.getTimezoneOffset();
console.log(minutes);
console.log(-minutes / 60);
36DST spring-forward traps
In America/New_York, 2026-03-08 local 02:00 jumps to 03:00 — that hour does not exist

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).

  1. DST spring-forward traps
js
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
A local calendar day can be 23 or 25 hours long

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.

  1. DST and the 24-hour day myth
js
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 (Stage 4) stores instants separately from calendars and timezones

Temporal.Now.instant() is "now"; Instant.from() parses a required-offset ISO string. Date.prototype.toTemporalInstant() bridges legacy Date when Temporal exists.

  1. Temporal Instant and Now
js
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
PlainDate is a calendar date with no time and no timezone — no off-by-one parse

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.

  1. Temporal PlainDate and ZonedDateTime
js
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
date-fns: tree-shakeable functions, always returns a new Date, format tokens like yyyy-MM-dd

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.

  1. date-fns vs dayjs
js
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 items
01First-class functions
Functions are values: assign, pass, return, store on objects or in arrays

A higher-order function takes or returns a function (map, then, onClick).

  1. First-class functions
js
function greet(name) {
  return `Hello ${name}`;
}
const alsoGreet = greet;
const printName = (fn) => fn("gore");
printName(alsoGreet); // "Hello gore"
02Function declarations
function name() {} is hoisted — callable before its line

Own this, arguments, and .prototype. Can be new'd. Name is required.

  1. Function declarations
js
add(2, 3); // 5
function add(a, b) {
  return a + b;
}
typeof add; // "function"
03Function expressions
const fn = function () {} is not hoisted as a function (var → undefined, let/const → TDZ)

A name after function is local — good for recursion.

  1. Function expressions
js
// 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); // ReferenceError
04Arrow functions
Lexical this / arguments / new.target

No .prototype; cannot be new'd. Expression body ⇒ implicit return. Objects need parens: () => ({}) No yield. Best for inline callbacks you own.

  1. Arrow functions
js
const sum = (a, b) => a + b;
const makeUser = (name) => ({ name });
// const bad = () => { name: "Ada" }; // labeled block, not an object
// new sum(); // TypeError: not a constructor
05Hoisting differences
Declaration: whole body hoisted

var fn = function: undefined until assigned. let/const / arrow: TDZ. In modules, a function declaration inside a block is block-scoped.

  1. Hoisting differences
js
console.log(typeof decl); // "function"
console.log(typeof expr); // "undefined" (var)
function decl() {}
var expr = function () {};
{
  function inner() {}
}
// inner(); // ReferenceError in modules
06arguments vs rest
arguments: array-like, not an array; only on non-arrows

Rest (...args) is a real array and works in arrows — prefer it. Arrows have no own arguments; they see the enclosing function's.

  1. arguments vs rest
js
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
Evaluated at call time, left to right, only when the arg is undefined (null and 0 are kept)

Later defaults may read earlier params.

  1. Default parameters
js
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 replaced
08this by function kind
Declaration / expression: this comes from the call site

Arrow: this from the enclosing scope; call/apply/bind cannot change it. Object method shorthand is a regular function (lost if extracted).

  1. this by function kind
js
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 undefined
09IIFE
Immediately Invoked Function Expression: private scope, run at once

Historic module pattern; still useful for one-shot setup.

  1. IIFE
js
const token = (() => JSON.parse("{}"))();
(function (g) {
  g.__boot = true;
})(globalThis);
10Callbacks
A function passed in to be invoked later

The callee decides when. Use a named function if you need removeEventListener or a clear stack.

  1. Callbacks
js
function fetchData(cb) {
  setTimeout(() => cb(null, { ok: true }), 100);
}
function onDone(err, data) {
  console.log(err || data);
}
fetchData(onDone);
11new vs arrows
Regular functions: new makes an object, sets [[Prototype]] to fn.prototype, returns that object unless you return another object

Arrows cannot construct.

  1. new vs arrows
js
function User(name) {
  this.name = name;
}
new User("Ada") instanceof User; // true
// new ((name) => ({ name }))(); // TypeError
12name and length
fn.name comes from the variable (or "bound name" after bind)

fn.length counts parameters before the first default or rest.

  1. name and length
js
const named = function demo(a, b = 1, ...rest) {};
named.name; // "demo"
named.length; // 1
named.bind(null).name; // "bound demo"

Closures

10 items
01What a closure is
A closure is a function plus its lexical environment: it remembers variables from where it was defined, even after the outer function returns
  1. What a closure is
js
function outer() {
  const secret = "ok";
  return function inner() {
    return secret;
  };
}
const fn = outer();
fn(); // "ok" — outer's frame is gone; inner still sees secret
02Lexical environment
Scope is decided by where the function is written, not where it is called

Lookup walks own env → outer env → … → global. The closure keeps that chain.

  1. Lexical environment
js
const x = "global";
function make() {
  const x = "outer";
  return function read() {
    return x;
  };
}
make()(); // "outer", not "global"
03Factory functions
Each outer call creates a fresh lexical environment

Returned functions from different calls do not share those locals.

  1. Factory functions
js
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
Locals are hidden; callers only use the functions you return

That is encapsulation without private class fields.

  1. Private counters
js
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; // undefined
05Stale closures in loops
var is function-scoped: every callback shares one i (the final value)

let creates a new binding per iteration. Classic setTimeout-in-for interview.

  1. Stale closures in loops
js
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
The function captures the binding, not a photocopy of the value

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).

  1. Stale closures in async / UI
js
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
An IIFE (or ES module body) runs once, keeps privates, exports an API
  1. Module pattern
js
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 hidden
08Memory leaks
A closure keeps its whole lexical env reachable — large objects and DOM nodes included

Timers, listeners, and module caches are the usual leaks. Dispose: clearInterval, removeEventListener, don't close over the node.

  1. Memory leaks
js
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 functions from the same outer call share bindings

Two outer calls → two independent environments.

  1. Shared vs separate environments
js
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 n
10Practical closures
once, memoize, and partial helpers are closures over private state
  1. Practical closures
js
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 again

Call, Apply & Bind

11 items
01How this is decided
this is set by the call site (how the function is invoked), not where it was written — except arrows, which take this from the enclosing scope

Five rules: default, implicit, explicit, new, lexical (arrow).

  1. How this is decided
js
function show() {
  return this;
}
show(); // undefined in modules/strict; globalThis in sloppy scripts
const obj = { show, tag: "obj" };
obj.show(); // implicit → this === obj
02this rules in detail
Default: bare call → undefined (strict) or global object (sloppy)

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.

  1. this rules in detail
js
const nested = { inner: { show } };
nested.inner.show(); // this === nested.inner, not nested
const detached = obj.show;
detached(); // default binding — this is NOT obj
03call — invoke now, args listed
fn.call(thisArg, a, b) runs fn immediately with this set to thisArg

Primitive thisArg is boxed (except in strict mode, where it stays as-is). Use when you already have individual arguments.

  1. call — invoke now, args listed
js
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
fn.apply(thisArg, [a, b]) is call with an array (or array-like)

Classic trick: Math.max.apply(null, nums) before spread existed. Today: fn.call(thisArg, ...arr) or Math.max(...nums).

  1. apply — invoke now, args as an array
js
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 equivalent
05bind — new function, this locked
fn.bind(thisArg, ...preset) returns a bound function

Original is unchanged. Later call/apply on the bound fn cannot replace this (except as a constructor). Extra bind args are prepended (partial application).

  1. bind — new function, this locked
js
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
call → run now, list arguments apply → run now, array of arguments bind → do not run; return a function with this (and optional args) fixed All three accept a thisArg

None of them mutate the original function.

  1. call vs apply vs bind
js
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); // 14
07Lost this on method extract
Passing obj.method as a callback strips the implicit receiver

setTimeout, addEventListener, map, and React props all do this.

  1. Lost this on method extract
js
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 counter
08Bound methods as callbacks
bind creates a stable function you can pass and later remove

Same bound reference is required for removeEventListener.

  1. Bound methods as callbacks
js
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 counter
09bind vs arrow
bind: creates a new exotic function; this is fixed; extra args can be preset; has .prototype and can be used with new (this then ignores the bound value)

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.

  1. bind vs arrow
js
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 widget
10Polyfill-level bind
A faithful bind: (1) remember the original fn and preset args, (2) apply thisArg unless the bound fn was called with new, (3) copy .prototype so instances still instanceof the original, (4) ignore later .bind / .call thisArg (bound this is sticky)
  1. Polyfill-level bind
js
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 sloppy mode, null/undefined thisArg becomes the global object

In strict mode (and ES modules), it stays null/undefined. Objects are used as-is; primitives are boxed in sloppy functions.

  1. Strict vs sloppy thisArg
js
function who() {
  return this;
}
who.call(null); // globalThis in sloppy; null in strict
who.call(42); // Number(42) in sloppy; 42 in strict

Currying

10 items
01What is currying
Currying turns f(a, b, c) into f(a)(b)(c): a chain of unary functions

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.

  1. What is currying
js
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 function
02Manual curry
Nested functions are the interview-friendly form

The innermost function does the real work; outer levels only capture arguments via closure.

  1. Manual curry
js
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); // 60
03Generic curry helper
Collect args until args.length >= fn.length, then call the original

Extra args in one call still count (not strictly unary). Pitfall: rest params and defaults make fn.length lie.

  1. Generic curry helper
js
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); // 24
04Curry vs partial application
Curry: keep returning a function until every formal parameter is filled

Partial: pre-fill some args now, accept the rest later — not necessarily one-at-a-time. Function.prototype.bind is partial application, not currying.

  1. Curry vs partial application
js
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 call
05Placeholders
A hole (_) lets you fix a later argument first (Ramda: R.__, lodash/fp: _)

Incoming values fill holes left-to-right, then append leftover args.

  1. Placeholders
js
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); // 5
06Real use cases
Specialized callbacks, config-first APIs, and reusable mappers

Curry once, pass the unary result to map / filter / addEventListener.

  1. Real use cases
js
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
compose(f, g, h)(x) runs right-to-left: f(g(h(x)))

Works cleanly when each step is unary — which currying gives you.

  1. compose
js
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
pipe(h, g, f)(x) runs left-to-right: f(g(h(x)))

Same idea as compose, usually easier to read as a data pipeline.

  1. pipe
js
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
Some interview puzzles use a terminator (empty call or valueOf) instead of fn.length

That is a running accumulator, not classic curry.

  1. Infinite curry vs fixed arity
js
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 valueOf
10Pitfalls
Over-currying hides arity and hurts stack traces

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.

  1. Pitfalls
js
function withDefault(a, b = 1) {
  return a + b;
}
withDefault.length; // 1 — curry would fire too early
function resty(...xs) {
  return xs;
}
resty.length; // 0

Promises

6 items
01A JavaScript Promise is an object that represents the eventu
A JavaScript Promise is an object that represents the eventual completion or failure of an asynchronous operation and its resulting value
js
// A JavaScript Promise has three states  in its lifecycle:
02Pending
The initial state

The async operation is still in progress. Neither resolve nor reject has been called.

  1. Pending
03Fulfilled
The operation completed successfully

resolve(value) was called.

  1. Fulfilled
04.then()
The .then() handler gets triggered
05Rejected
The operation failed

reject(error) was called.

  1. Rejected
06.catch()
The .catch() handler gets triggered
js
// 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 items
01Error object
Runtime exceptions are Error (or a subclass): name, message, stack, and (ES2022) cause

You can throw any value — don't; you lose the stack.

  1. Error object
js
const err = new Error("boom");
err.name; // "Error"
err.message; // "boom"
err.stack; // engine-specific frames
02ReferenceError
The binding does not exist, or it is still in the TDZ (let / const / class)

Different from a declared variable whose value is undefined.

  1. ReferenceError
js
// 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 names
03TypeError
Wrong type: call a non-function, read null/undefined, assign to const or a frozen object (throws in strict / modules)
  1. TypeError
js
// 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 sloppy
04SyntaxError
The parser never built a program

You cannot catch it in the same file. You can catch it from JSON.parse, eval, or new Function.

  1. SyntaxError
js
// if (true { }  // Unexpected token '{'
try {
  JSON.parse("{");
} catch (e) {
  e instanceof SyntaxError; // true
}
05RangeError
A number or length is outside the allowed range

Deep recursion is "Maximum call stack size exceeded" (V8). Firefox may use InternalError.

  1. RangeError
js
// new Array(-1);
// (10).toPrecision(500);
function recurse(k) {
  return recurse(k + 1);
}
06URIError
decodeURI / encodeURI throw on malformed sequences

An EvalError exists for history; engines almost never throw it now.

  1. URIError
js
decodeURIComponent("a%"); // URI malformed
07throw
throw expr; exits the current function

Prefer new SomeError(msg) so callers can use instanceof and still have a stack.

  1. throw
js
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"); // 21
08try / catch / finally
finally always runs (success, throw, or return)

A return in finally wins over try. Optional catch binding: catch { } (ES2019).

  1. try / catch / finally
js
function read() {
  try {
    return parseAge("no");
  } catch (e) {
    console.log(e.message);
    return 0;
  } finally {
    console.log("cleanup");
  }
}
read(); // logs message, then "cleanup", returns 0
09Rethrow
Handle what you know; rethrow the rest

No catch-if syntax — use if + throw.

  1. Rethrow
js
try {
  parseAge(-1);
} catch (e) {
  if (e instanceof RangeError) console.log("bad range");
  else throw e;
}
10Async errors
try/catch around setTimeout only wraps scheduling, not the callback

await inside try/catch (or .catch). throw in async rejects the promise.

  1. Async errors
js
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
Extend Error, call super(message), set this.name

Keep instanceof working.

  1. Custom errors
js
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
Second argument { cause } (ES2022) wraps a lower-level error

DevTools shows the chain; read it later as err.cause.

  1. Error.cause
js
try {
  JSON.parse("{");
} catch (e) {
  throw new Error("invalid config", { cause: e });
}
13AggregateError
One error that holds several

Promise.any rejects with this when every promise rejects. errors is the array of reasons.

  1. AggregateError
js
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; // 1

ES6

10 items
01Here’s a concise overview of ES6 (ECMAScript 2015) features
Here’s a concise overview of ES6 (ECMAScript 2015) features
02Let and Const
let and const are block-scoped
  1. Let and Const
js
// let is mutable, const is immutable (for primitive values).

let a = 10;
a = 20;

const b = 30;
// b = 40;  Error
03Arrow Functions
Shorter syntax and lexical this binding
  1. Arrow Functions
js
const sum = (a, b) => a + b;
console.log(sum(2, 3)); // 5
04Template Literals
Multi-line strings and expression interpolation
  1. Template Literals
js
const Name = "Gore";
console.log(`Hello, ${Name}!`);
05Destructuring Assignment
Extract values from arrays or objects
  1. Destructuring Assignment
js
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
Set default values for function parameters
  1. Default Parameters
js
function greet(name = "Guest") {
  console.log(`Hello, ${name}`);
}
greet(); // Hello, Guest
07Rest and Spread Operators ... to collect or expand values
  1. Rest and Spread Operators ... to collect or expand values.
js
// 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
Handle async operations
  1. Promises
js
const fetchData = () =>
  new Promise((resolve) => {
    setTimeout(() => resolve("Done"), 1000);
  });

fetchData().then(console.log);
09For...of Loop
Iterates over iterable objects like arrays
  1. For...of Loop
js
for (const num of [1, 2, 3]) {
  console.log(num);
}
10Map and Set
New data structures
  1. Map and Set
js
const set = new Set([1, 2, 2]); // {1, 2}
const map = new Map();
map.set("key", "value");

Regular Expressions

9 items
01Key Regex Building Blocks
Key Regex Building Blocks
02Character Classes
  1. Character Classes
js
// \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")); // true
03Quantifiers
  1. Quantifiers
js
// + → 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
  1. Anchors
js
// ^ → start of string
// $ → end of string

console.log(/^hello/.test("hello world")); // true
console.log(/world$/.test("hello world")); // true
05Groups & Alternation
  1. Groups & Alternation
js
// (abc) → group
// | → OR

console.log(/cat|dog/.test("dog")); // true
06Escaping
  1. Escaping
js
// Match special chars (. ^ $ * + ? { } [ ] | ( )), escape with \.

console.log(/\./.test("file.txt")); // true
07Email
/^[\w.-]+@[\w.-]+\.\w{2,}$/
  1. Email
08Phone Number (basic, 10 digits)
/^\d{10}$/
  1. Phone Number (basic, 10 digits)
09Date (YYYY-MM-DD)
/^\d{4}-\d{2}-\d{2}$/
  1. Date (YYYY-MM-DD)
js
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 only

Storage

25 items
01When to use each
localStorage — persist across tabs and restarts (prefs, cached JSON)

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.

  1. When to use each
js
const pick = {
  theme: "localStorage",
  wizardStep: "sessionStorage",
  sessionId: "cookie (server-set, HttpOnly)",
  offlineNotes: "IndexedDB",
};
console.log(pick.theme);
02localStorage set and get
Same-origin key/value store

Survives refresh and browser restart. All values are strings. Missing keys return null, not undefined.

  1. localStorage set and get
js
localStorage.setItem("theme", "dark");
const theme = localStorage.getItem("theme"); // "dark"
console.log(theme);
console.log(localStorage.getItem("missing")); // null
03localStorage remove and clear
removeItem deletes one key

clear() wipes every key for this origin. Prefer removeItem so you do not delete unrelated keys.

  1. localStorage remove and clear
js
localStorage.setItem("a", "1");
localStorage.setItem("b", "2");
localStorage.removeItem("a");
console.log(localStorage.getItem("a")); // null
04localStorage key and length
length is the number of keys

key(i) reads the name at that index. Index order is not something you should rely on.

  1. localStorage key and length
js
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
API is identical to localStorage, but data is per-tab (not per-origin shared)

A duplicate tab usually gets a copy; a new tab starts empty. Closing the tab deletes it. Refresh keeps it.

  1. sessionStorage tab scope
js
sessionStorage.setItem("step", "2");
console.log(sessionStorage.getItem("step")); // "2"
sessionStorage.removeItem("step");
06Values are always strings
Numbers, booleans, and objects are coerced with ToString

[object Object] is the classic bug. Always JSON.stringify objects.

  1. Values are always strings
js
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
Round-trip objects and arrays with JSON.stringify / JSON.parse

Guard parse — empty, null, or corrupt strings throw.

  1. JSON serialize for objects
js
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); // Gore
08JSON serialize pitfalls
undefined in objects is dropped; in arrays it becomes null

Date becomes an ISO string. Map/Set become {}. Functions and symbols are omitted. Circular refs throw. NaN and Infinity become null.

  1. JSON serialize pitfalls
js
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
localStorage / sessionStorage are small (~5MB per origin, browser-dependent)

Writes can throw QuotaExceededError (or a DOMException). Always try/catch.

  1. QuotaExceededError
js
try {
  localStorage.setItem("cache", "x".repeat(10_000_000));
} catch (err) {
  if (err.name === "QuotaExceededError") {
    localStorage.removeItem("cache");
  }
}
10Same-origin isolation
Storage is keyed by origin: scheme + host + port

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.

  1. Same-origin isolation
js
console.log(location.origin); // e.g. "http://localhost:3000"
11storage event
Fires in *other* same-origin documents when localStorage changes

The writing tab does not get the event. Other tab: localStorage.setItem(...). sessionStorage almost never notifies other tabs (tab-scoped).

  1. storage event
js
window.addEventListener("storage", (e) => {
  console.log(e.key, e.oldValue, e.newValue, e.url);
  console.log(e.storageArea === localStorage);
});
12Read document.cookie
One semicolon-separated string

HttpOnly cookies are invisible to JS. There is no API to read attributes (Path, SameSite) back out.

  1. Read document.cookie
js
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
Assigning document.cookie sets *one* cookie; it does not replace the whole jar

Default: session cookie (deleted when the browser closes), current path.

  1. Write document.cookie
js
document.cookie = "theme=dark";
document.cookie = "locale=en";
console.log(document.cookie); // both still present
14Cookie expires and max-age
expires is an HTTP-date

max-age is seconds from now (usually preferred). max-age=0 (or a past expires) deletes the cookie.

  1. Cookie expires and max-age
js
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
Path defaults to the current URL path — a cookie set on /notes may not be sent to /learn

Use Path=/ for the whole site. Domain=example.com shares across subdomains (leading dot is optional now).

  1. Cookie path and domain
js
document.cookie = "theme=dark; Path=/";
document.cookie = "theme=dark; Domain=example.com; Path=/";
16Secure HttpOnly SameSite
Secure — only sent on HTTPS (localhost is special-cased)

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.

  1. Secure HttpOnly SameSite
js
document.cookie = "prefs=1; Path=/; Secure; SameSite=Lax";
console.log(document.cookie.includes("prefs"));
17Encode cookie values
Values can break on ; , = and spaces

Encode on write, decode on read. Cookie names should stay simple tokens.

  1. Encode cookie values
js
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
Re-set the same name with max-age=0 (or a past expires)

Path and Domain must match the original or the browser will not delete it.

  1. Delete a cookie
js
document.cookie = "theme=; Path=/; max-age=0";
document.cookie = "theme=; Domain=example.com; Path=/; max-age=0";
19Cookies vs Web Storage
Cookies: ~4KB each, sent on matching requests (payload + CSRF risk)

Web Storage: ~5MB, never sent automatically, JS-only. Never put secrets in localStorage — any XSS can read them.

  1. Cookies vs Web Storage
js
const sentWithEveryRequest = "cookies";
const staysInTheBrowser = "localStorage / sessionStorage / IndexedDB";
console.log(sentWithEveryRequest, staysInTheBrowser);
20IndexedDB open
Async, transactional, origin-scoped DB for large structured data

onupgradeneeded runs when the version is new or higher.

  1. IndexedDB open
js
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
Stores are like tables

Create them only inside onupgradeneeded. keyPath uses a field on the value. autoIncrement assigns keys.

  1. IndexedDB object store
js
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
Transactions: readonly | readwrite

put upserts; add fails if the key exists. Work must happen while the transaction is active (no awaiting extra I/O in between).

  1. IndexedDB put and add
js
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
get(key) returns the record or undefined

getAll() pulls a snapshot.

  1. IndexedDB get
js
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
delete(key) / clear() for writes

openCursor walks records without loading all.

  1. IndexedDB delete and cursor
js
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
navigator.storage.estimate() reports usage vs quota (IndexedDB + Cache API)

persist() asks the browser not to evict the origin under storage pressure.

  1. Storage quotas
js
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 items
01fetch GET
fetch(url) defaults to GET and returns a Promise<Response>

The promise rejects only on network failure, not on 404/500.

  1. fetch GET
js
const res = await fetch("https://api.example.com/users");
const data = await res.json();
console.log(data);
02Response.ok
ok is true when status is 200–299

Always check it before trusting the body. status / statusText are the raw HTTP code and reason.

  1. Response.ok
js
const res2 = await fetch("/api/user");
if (!res2.ok) {
  throw new Error(`${res2.status} ${res2.statusText}`);
}
console.log(res2.status); // 200
03Parse JSON
response.json() reads the body once and parses it

Empty or non-JSON bodies throw. Also: text(), blob(), arrayBuffer(), formData().

  1. Parse JSON
js
const res3 = await fetch("/api/me");
const me = await res3.json();
console.log(me.id);
04POST JSON
Send a string body and set Content-Type

JSON.stringify the object yourself.

  1. POST JSON
js
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); // 201
05Custom headers
Headers can be an object or a Headers instance

Forbidden headers (Cookie, Host, Origin, …) are controlled by the browser.

  1. Custom headers
js
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
Build the query string with URL / URLSearchParams — do not concatenate by hand
  1. Query parameters
js
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
Pass signal to fetch

abort() rejects the fetch with an AbortError. One controller can abort several fetches that share the same signal.

  1. AbortController
js
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
fetch has no timeout option

Abort after N ms, then always clear the timer.

  1. Timeout pattern
js
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
Retry network failures and 5xx

Do not blindly retry 4xx or POST without care. Backoff: wait base * 2^attempt (and optionally add jitter).

  1. Retry with backoff
js
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
FormData builds multipart/form-data

Append strings or File/Blob values. Use this for file inputs — not JSON.stringify.

  1. FormData uploads
js
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
Do not set Content-Type yourself — the browser adds the multipart boundary

Setting application/json or a bare multipart type breaks the upload.

  1. FormData Content-Type
js
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
same-origin (default) — cookies on same-origin requests only

include — cookies on cross-origin too (server must allow credentials). omit — never send cookies.

  1. credentials
js
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
Browser rule: JS on origin A cannot *read* origin B unless B sends Access-Control-Allow-Origin (specific origin, or *)

curl is unaffected. Credentials cannot use *. They need a concrete origin + Allow-Credentials: true.

  1. CORS mental model
js
const corsRes = await fetch("https://api.other.com/data");
console.log(corsRes.ok);
14Simple vs preflight
Simple: GET/POST/HEAD + a few headers + simple Content-Type → no OPTIONS

Anything else (PUT, JSON Content-Type, custom headers) → preflight OPTIONS first. Preflight asks: Access-Control-Request-Method / Headers; server answers Allow-*.

  1. Simple vs preflight
js
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
cors (default) — follow CORS; opaque failures throw / hide the body

no-cors — you get an opaque response (status 0, body unreadable). Rarely useful. same-origin — throw if the URL is cross-origin.

  1. fetch mode
js
await fetch("/api/me", { mode: "same-origin" });
await fetch("https://cdn.example.com/hit", { mode: "no-cors" }); // opaque
16Network vs HTTP errors
Network / CORS / abort → fetch rejects (TypeError or AbortError)

404 / 500 → fetch resolves; you must check response.ok.

  1. Network vs HTTP errors
js
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
res.body is a ReadableStream

Read chunks before the full payload arrives. Useful for SSE-like text, logs, or large files. json() waits for the whole body.

  1. Streaming text
js
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
The body is a one-shot stream

json() then text() throws. clone() before reading if you need two consumers.

  1. response.clone
js
const res18 = await fetch("/api/me");
const copy = res18.clone();
console.log(await res18.json());
console.log(await copy.text());
19PUT PATCH DELETE
method selects the verb

DELETE often has no body; PATCH/PUT usually send JSON.

  1. PUT PATCH DELETE
js
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
application/x-www-form-urlencoded — HTML form default, not multipart

fetch sets the Content-Type when the body is URLSearchParams.

  1. URLSearchParams body
js
const params = new URLSearchParams({ email: "a@b.com", remember: "1" });
await fetch("/login", { method: "POST", body: params });
21Blob download
res.blob() gives a file-like object

Object URLs can trigger a download.

  1. Blob download
js
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
default — browser HTTP cache rules

no-store — always hit the network. reload — network then update cache. force-cache / only-if-cached — prefer cache.

  1. cache option
js
await fetch("/api/config", { cache: "no-store" });
await fetch("/icons/app.svg", { cache: "force-cache" });
23redirect option
follow (default) — follow 3xx

manual — you see the redirect response. error — reject on redirect.

  1. redirect option
js
const res23 = await fetch("/old-path", { redirect: "follow" });
console.log(res23.redirected, res23.url);
24Parallel requests
Kick off fetches together, then Promise.all

All fail if one rejects. Promise.allSettled if you want partial results.

  1. Parallel requests
js
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
try/catch for network + AbortError

Check ok for HTTP errors. Read an error payload when the server sends JSON errors.

  1. Error handling pattern
js
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 items
01IntersectionObserver
Fires when a target enters or leaves a root (viewport by default)

Use for lazy images, infinite scroll, and "was this section seen?".

  1. IntersectionObserver
js
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
root — scroll container (null = viewport)

rootMargin — CSS-like grow/shrink. threshold — 0..1 (or an array). 0.25 = callback when 25% is visible.

  1. IntersectionObserver options
js
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
unobserve drops one target

disconnect() stops every target at once. After a one-shot lazy-load, unobserve so the callback stops firing.

  1. unobserve and disconnect
js
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
Fires when an element's content-box size changes (not window.resize)

Prefer this over measuring in a window resize listener. Cleanup: ro.unobserve(el) or ro.disconnect().

  1. ResizeObserver
js
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
Fires when the DOM tree changes: children, attributes, or text

Use for integrating with third-party widgets — not as a React state substitute.

  1. MutationObserver
js
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
childList — add/remove kids

attributes — attr changes (filter with attributeFilter). subtree — watch descendants. characterData — text node changes. disconnect, then takeRecords() to drain queued mutations.

  1. MutationObserver options
js
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
Workers run JS on a background thread — no DOM, no window

Offload CPU work (parse, crypto, canvas pixel math) so the UI stays responsive.

  1. Create a Web Worker
js
const worker = new Worker("/worker.js", { type: "module" });
console.log(worker); // Dedicated: one page. SharedWorker: many tabs.
08postMessage
Structured-clone data across the thread boundary (no functions)

Transferables (ArrayBuffer) move ownership instead of copying. worker.js: self.onmessage = (e) => self.postMessage({ result: e.data.n * 2 });

  1. postMessage
js
const fibWorker = new Worker("/worker.js");
fibWorker.postMessage({ type: "fib", n: 40 });
fibWorker.onmessage = (e) => console.log("result", e.data);
09Worker error and terminate
onerror / onmessageerror catch script and clone failures

terminate() kills the worker from the page; self.close() from inside.

  1. Worker error and terminate
js
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
Run low-priority work when the browser is idle (between frames / input)

deadline.timeRemaining() is leftover idle ms. Do not do long tasks here.

  1. requestIdleCallback
js
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
timeout: N forces the callback after N ms even if the page never goes idle

cancelIdleCallback cancels a pending id. Safari support is late — feature-detect.

  1. Idle timeout option
js
const idle2 = requestIdleCallback(
  (deadline) => {
    console.log("idle or forced", deadline.didTimeout, deadline.timeRemaining());
  },
  { timeout: 2000 },
);
cancelIdleCallback(idle2);
if (typeof requestIdleCallback !== "function") {
  setTimeout(() => {}, 1);
}
12requestAnimationFrame
Schedules work just before the next paint

Use for animations and visual sync. One callback per frame; batch DOM reads, then writes, to avoid layout thrash.

  1. requestAnimationFrame
js
let rafId = requestAnimationFrame(function tick(ts) {
  console.log("frame", ts);
  rafId = requestAnimationFrame(tick);
});
13cancelAnimationFrame
Cancel the next tick — required when the animation should stop (tab hidden, component unmount, user pause)
  1. cancelAnimationFrame
js
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
Parses a CSS media query and tells you if it currently matches

Prefer this over reading window.innerWidth for breakpoint logic.

  1. matchMedia
js
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
Listen for viewport / preference changes (width, prefers-color-scheme, …)

Use addEventListener("change") — addListener is deprecated. Cleanup: dark.removeEventListener("change", syncTheme).

  1. matchMedia change
js
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
document.hidden / visibilityState tell you if the tab is visible

"visible" | "hidden" (prerender/unloaded exist in older notes).

  1. Visibility API
js
console.log(document.hidden);
console.log(document.visibilityState); // "visible" | "hidden"
document.addEventListener("visibilitychange", () => {
  console.log("now", document.visibilityState);
});
17Pause when hidden
Stop rAF, videos, and polling while the tab is hidden

Saves CPU and battery; resume on visible.

  1. Pause when hidden
js
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
Boolean guess: the browser thinks it has a network

true does not mean the API is reachable (captive portal, DNS fail).

  1. navigator.onLine
js
console.log(navigator.onLine); // true | false
if (!navigator.onLine) {
  console.log("queue writes in IndexedDB until we reconnect");
}
19online and offline events
window fires "offline" / "online" when the browser flips that flag

Still verify with a real fetch — the event is not a heartbeat.

  1. online and offline events
js
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
IntersectionObserver — is this node on screen?

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.

  1. Pick the right API
js
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 items
01at()
The at() method returns the element at a given index

Negative indexes count from the end.

js
const arr = [10, 20, 30, 40];
console.log(arr.at(1)); // 20
console.log(arr.at(-1)); // 40
02concat()
The concat() method merges arrays into a new array without modifying originals
js
const a1 = [1, 2],
  a2 = [3, 4];
console.log(a1.concat(a2)); // [1, 2, 3, 4]
03copyWithin()
The copyWithin() method copies part of the array to another location in the same array
js
const arr1 = [1, 2, 3, 4, 5];
console.log(arr1.copyWithin(0, 3)); // [4, 5, 3, 4, 5]
04entries()
The entries() method returns an iterator with [index, value] pairs
js
for (const [i, v] of ["a", "b"].entries()) {
  console.log(i, v); // 0 "a", 1 "b"
}
05every()
The every() method tests if all elements pass the provided test (returns boolean)
js
console.log([2, 4, 6].every((n) => n % 2 === 0)); // true
06fill()
The fill() method replaces elements with a static value from start to end
js
const arr2 = [1, 2, 3, 4];
console.log(arr2.fill(0, 1, 3)); // [1, 0, 0, 4]
07filter()
The filter() method creates a new array with elements that pass the test
js
console.log([10, 20, 30].filter((n) => n > 15)); // [20, 30]
08find()
The find() method returns the first element that satisfies the condition
js
console.log([5, 12, 8].find((n) => n > 10)); // 12
09findIndex()
The findIndex() method returns the index of the first element satisfying the test
js
console.log([5, 12, 8].findIndex((n) => n > 10)); // 1
10findLast()
The findLast() method returns the last element that satisfies the condition

console.log([5, 12, 8].findLast((n) => n > 10)); // 12

11findLastIndex()
The findLastIndex() method returns the index of the last element satisfying the test

console.log([5, 12, 50].findLastIndex((n) => n > 10)); // 2

12flat()
The flat() method flattens nested arrays into a new array up to given depth
js
console.log([1, [2, [3]]].flat(2)); // [1, 2, 3]
13flatMap()
The flatMap() method maps each element and flattens the result into a new array
js
console.log([1, 2, 3].flatMap((n) => [n, n * 2])); // [1, 2, 2, 4, 3, 6]
14forEach()
The forEach() method executes a function once per array element
js
[1, 2, 3].forEach((n) => console.log(n * 2)); // 2, 4, 6
15includes()
The includes() method checks if an array contains a value
js
console.log([1, 2, 3].includes(2)); // true
16indexOf()
The indexOf() method returns the first index of a value, or -1 if not found
js
console.log(["a", "b", "a"].indexOf("a")); // 0
17lastIndexOf()
The lastIndexOf() method returns the last index of a value, or -1 if not found
js
console.log(["a", "b", "a"].lastIndexOf("a")); // 2
18join()
The join() method joins all elements into a string with a separator
js
console.log(["a", "b", "c"].join("-")); // "a-b-c"
19keys()
The keys() method returns an iterator of indexes (keys)
js
console.log([...["a", "b"].keys()]); // [0, 1]
20map()
The map() method creates a new array with results of applying a function
js
console.log([1, 2, 3].map((n) => n * 2)); // [2, 4, 6]
21pop()
The pop() method removes the last element and returns it
js
const arr3 = [1, 2, 3];
console.log(arr3.pop()); // 3
console.log(arr3); // [1, 2]
22push()
The push() method adds elements to the end and returns the new length
js
const arr4 = [1];
console.log(arr4.push(2, 3)); // 3
console.log(arr4); // [1, 2, 3]
23reduce()
The reduce() method reduces array to a single value by accumulator
js
console.log([1, 2, 3].reduce((acc, val) => acc + val, 0)); // 6
24reduceRight()
The reduceRight() method works like reduce but from right-to-left
js
console.log(["a", "b", "c"].reduceRight((acc, val) => acc + val)); // "cba"
25reverse()
The reverse() method reverses array in place
js
const arr5 = [1, 2, 3];
arr5.reverse();
console.log(arr5); // [3, 2, 1]
26shift()
The shift() method removes the first element and returns it
js
const arr6 = [1, 2, 3];
console.log(arr6.shift()); // 1
console.log(arr6); // [2, 3]
27unshift()
The unshift() method adds elements at the beginning and returns new length
js
console.log(arr6.unshift(0)); // 3
console.log(arr6); // [0, 2, 3]
28slice()
The slice() method returns a shallow copy of part of an array.<- don't changes original array
js
console.log([1, 2, 3, 4].slice(1, 3)); // [2, 3]
29splice()
The splice() method changes contents by removing/replacing/adding

<- changes original array

js
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()
The some() method tests if any element passes the provided test
js
console.log([1, 2, 3].some((n) => n > 2)); // true
31sort()
The sort() method sorts array in place (default: as strings)
js
const arr8 = [40, 1, 5];
arr8.sort((a, b) => a - b);
console.log(arr8); // [1, 5, 40]
32toLocaleString()
The toLocaleString() method returns localized string of array contents
js
console.log([1000, new Date("2020-01-01")].toLocaleString("en-US"));
// "1,000, 1/1/2020, 12:00:00 AM"
33toString()
The toString() method returns a string of array elements (like join with comma)
js
console.log([1, 2, 3].toString()); // "1,2,3"
34values()
The values() method returns an iterator of values
js
for (const v of ["a", "b"].values()) {
  console.log(v); // "a", "b"
}
35Array.isArray() (static)
The Array.isArray() (static method) checks if a value is an array
js
console.log(Array.isArray([1, 2])); // true
console.log(Array.isArray("hi")); // false
36Array.from() (static)
The Array.from() (static method) creates an array from iterable or array-like
js
console.log(Array.from("123")); // ["1", "2", "3"]
37Array.of() (static)
The Array.of() (static method) creates an array from arguments
js
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: 2
38interview
interview
MethodCreates New ArrayUpdates Existing ArrayReturns
forEach❌ No✅ Yes (if you modify it)undefined
map✅ Yes❌ NoNew array
filter✅ Yes❌ NoNew array (filtered)
reduce❌ No❌ NoSingle value (any type)

Object Methods

25 items
01Object.assign()
The Object.assign() method copies properties from source objects to a target object
js
const target = { a: 1 };
const source = { b: 2 };
console.log(Object.assign(target, source)); // { a: 1, b: 2 }
02Object.create()
The Object.create() method creates a new object with the given prototype
js
const proto = { greet: () => "hi" };
const obj = Object.create(proto);
console.log(obj.greet()); // "hi"
03Object.defineProperty()
The Object.defineProperty() method adds/updates a property with descriptors
js
const obj1 = {};
Object.defineProperty(obj1, "x", { value: 42, writable: false });
console.log(obj1.x); // 42
04Object.defineProperties()
The Object.defineProperties() method defines multiple properties at once
js
const obj2 = {};
Object.defineProperties(obj2, {
  a: { value: 1 },
  b: { value: 2, writable: true },
});
console.log(obj2); // { a: 1, b: 2 }
05Object.entries()
The Object.entries() method returns [key, value] pairs as an array
js
console.log(Object.entries({ x: 1, y: 2 })); // [["x", 1], ["y", 2]]
06Object.fromEntries()
The Object.fromEntries() method creates an object from [key, value] pairs
js
console.log(
  Object.fromEntries([
    ["x", 1],
    ["y", 2],
  ])
); // { x: 1, y: 2 }
07Object.freeze()
The Object.freeze() method freezes an object (no add/remove/change)
js
const frozen = Object.freeze({ a: 1 });
frozen.a = 2;
console.log(frozen.a); // 1
08Object.isFrozen()
The Object.isFrozen() method checks if object is frozen
js
console.log(Object.isFrozen(frozen)); // true
09Object.seal()
The Object.seal() method seals an object (no add/remove, but can change existing)
js
const sealed = Object.seal({ a: 1 });
sealed.a = 2;
console.log(sealed); // { a: 2 }
10Object.isSealed()
The Object.isSealed() method checks if object is sealed
js
console.log(Object.isSealed(sealed)); // true
11Object.preventExtensions()
The Object.preventExtensions() method prevents adding new properties
js
const o1 = { a: 1 };
Object.preventExtensions(o1);
o1.b = 2;
console.log(o1); // { a: 1 }
12Object.isExtensible()
The Object.isExtensible() method checks if new props can be added
js
console.log(Object.isExtensible(o1)); // false
13Object.getOwnPropertyDescriptor()
The Object.getOwnPropertyDescriptor() returns descriptor of a property
js
const obj3 = { x: 10 };
console.log(Object.getOwnPropertyDescriptor(obj3, "x"));
// { value: 10, writable: true, enumerable: true, configurable: true }
14Object.getOwnPropertyDescriptors()
The Object.getOwnPropertyDescriptors() returns descriptors of all props
js
console.log(Object.getOwnPropertyDescriptors(obj3));
15Object.getOwnPropertyNames()
The Object.getOwnPropertyNames() returns all string keys (including non-enumerable)
js
console.log(Object.getOwnPropertyNames({ a: 1, b: 2 })); // ["a", "b"]
16Object.getOwnPropertySymbols()
The Object.getOwnPropertySymbols() returns all symbol keys
js
const sym = Symbol("id");
const obj4 = { [sym]: 123 };
console.log(Object.getOwnPropertySymbols(obj4)); // [ Symbol(id) ]
17Object.getPrototypeOf()
The Object.getPrototypeOf() returns prototype of an object
js
console.log(Object.getPrototypeOf([]) === Array.prototype); // true
18Object.setPrototypeOf()
The Object.setPrototypeOf() sets the prototype of an object
js
const animal = { eats: true };
const rabbit = {};
Object.setPrototypeOf(rabbit, animal);
console.log(rabbit.eats); // true
19Object.hasOwn()
The Object.hasOwn() method checks if object has a property as its own (not from prototype)
js
const obj5 = { a: 1 };
console.log(Object.hasOwn(obj5, "a")); // true
console.log(Object.hasOwn(obj5, "b")); // false
20Object.keys()
The Object.keys() method returns an array of object’s own keys
js
console.log(Object.keys({ a: 1, b: 2 })); // ["a", "b"]
21Object.values()
The Object.values() method returns an array of object’s own values
js
console.log(Object.values({ a: 1, b: 2 })); // [1, 2]
22Object.is()
The Object.is() method compares two values (like === but handles NaN correctly)
js
console.log(Object.is(NaN, NaN)); // true
console.log(Object.is(0, -0)); // false
23Object.groupBy()
The Object.groupBy() (ES2024) groups array elements into an object based on a function
js
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 Exists
24'name' in obj; // ✅ true
'name' in obj; // ✅ true
25obj.hasOwnProperty('city'); // ✅ true
obj.hasOwnProperty('city'); // ✅ true
js
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 items
01Example
js
const str = "Hello";
02at()
The at() method returns the character at the given index, supports negative indices
js
console.log(str.length); // 5
console.log(str.at(1)); // "e"
console.log(str.at(-1)); // "o"
03charAt()
The charAt() method returns the character at a specific index
js
console.log(str.charAt(0)); // "H"
04charCodeAt()
The charCodeAt() method returns the Unicode value of the character at the given index
js
console.log(str.charCodeAt(0)); // 72
05codePointAt()
The codePointAt() method returns the Unicode code point value (handles emojis, symbols too)
js
console.log("😊".codePointAt(0)); // 128522
06concat()
The concat() method joins two or more strings
js
console.log("Hello".concat(" ", "World")); // "Hello World"
07includes()
The includes() method checks if a string contains another substring
js
console.log(str.includes("Hell")); // true
console.log(str.includes("hey")); // false
08endsWith()
The endsWith() method checks if a string ends with the specified characters
js
console.log(str.endsWith("lo")); // true
console.log(str.endsWith("He")); // false
09startsWith()
The startsWith() method checks if a string starts with the specified characters
js
console.log(str.startsWith("He")); // true
10indexOf()
The indexOf() method returns the first index of a substring, or -1 if not found
js
console.log(str.indexOf("l")); // 2
11lastIndexOf()
The lastIndexOf() method returns the last index of a substring, or -1 if not found
js
console.log(str.lastIndexOf("l")); // 3
12match()
The match() method searches using regex and returns an array of matches or null
js
console.log("cat bat mat".match(/at/g)); // ["at", "at", "at"]
13matchAll()
The matchAll() method returns an iterator of all regex matches
js
for (const m of "test1test2".matchAll(/test\d/g)) {
  console.log(m[0]); // "test1", "test2"
}
14padStart()
The padStart() method pads the string with another string at the start until length is reached
js
console.log("5".padStart(3, "0")); // "005"
15padEnd()
The padEnd() method pads the string with another string at the end until length is reached
js
console.log("5".padEnd(3, "0")); // "500"
16repeat()
The repeat() method returns a new string repeating the given string
js
console.log("ha".repeat(3)); // "hahaha"
17replace()
The replace() method replaces the first match with another string
js
console.log("Hello World".replace("World", "JS")); // "Hello JS"
18replaceAll()
The replaceAll() method replaces all matches of a substring or regex
js
console.log("a-b-c".replaceAll("-", "|")); // "a|b|c"
19search()
The search() method searches using regex and returns the index of the first match
js
console.log("hello".search(/l/)); // 2
20slice()
The slice() method extracts part of a string and returns it
js
console.log("Hello".slice(1, 4)); // "ell"
21substring()
The substring() method extracts characters between two indices (cannot use negative values)
js
console.log("Hello".substring(1, 4)); // "ell"
22substr()
The substr() method extracts part of a string based on start index and length (deprecated, but seen in legacy code)
js
console.log("Hello".substr(1, 3)); // "ell"
23split()
The split() method splits a string into an array based on a separator
js
console.log("a,b,c".split(",")); // ["a", "b", "c"]
24toLowerCase()
The toLowerCase() method converts the string to lowercase
js
console.log("HELLO".toLowerCase()); // "hello"
25toUpperCase()
The toUpperCase() method converts the string to uppercase
js
console.log("hello".toUpperCase()); // "HELLO"
26trim()
The trim() method removes whitespace from both ends
js
console.log("   hi   ".trim()); // "hi"
27trimStart()
The trimStart() method removes whitespace from the beginning
js
console.log("   hi".trimStart()); // "hi"
28trimEnd()
The trimEnd() method removes whitespace from the end
js
console.log("hi   ".trimEnd()); // "hi"
29valueOf()
The valueOf() method returns the primitive value of a String object
js
console.log(new String("Hello").valueOf()); // "Hello"
30toString()
The toString() method returns the string representation of the object
js
console.log((123).toString()); // "123"
31localeCompare()
The localeCompare() method compares two strings based on locale

Returns -1 (smaller), 0 (equal), 1 (greater).

js
console.log("a".localeCompare("b")); // -1
32normalize()
The normalize() method returns the Unicode Normalization Form of a string
js
console.log("\u00F1".normalize("NFD")); // "ñ"
33fromCharCode()
The fromCharCode() (static on String) creates a string from UTF-16 code units
js
console.log(String.fromCharCode(72, 101, 108, 108, 111)); // "Hello"
34fromCodePoint()
The fromCodePoint() (static on String) creates a string from Unicode code points
js
console.log(String.fromCodePoint(128522)); // "😊"
35raw()
The raw() method (static on String) is used in template literals to get raw strings
js
console.log(String.raw`Hello\nWorld`); // "Hello\nWorld"