Explorer
JavaScript

Web APIs: DOM, Events, and Storage

JavaScript Theory & Concepts

Web APIs: DOM, Events, and Storage

Browser host platform capabilities, DOM tree manipulation, and client-side persistence.

📖 The Story & Real-World Analogy

The Customer and the Supermarket Shelves

"The JavaScript Engine is a customer walking down the aisles with a shopping cart. The customer only knows how to think and count. The Browser environment is the giant supermarket providing shelves of equipment: • **The DOM**: The produce displays that you can inspect, rearrange, or slice. • **Events**: The customer service bell that rings whenever a shopper taps an item. • **Web Storage**: The customer lockers in the lobby (`localStorage` keeps items safe overnight, while `sessionStorage` lockers are cleaned out the second you exit the building)."

Web APIs are not defined by ECMAScript; they are host platform APIs exposed by browser engines (in C++) to allow JavaScript to interact with documents, user inputs, and device storage.

⚙️ How It Works Under The Hood (Step-by-Step)
1

The DOM Tree and Traversal

The HTML document is parsed into a tree of Nodes. Use `querySelector`, `querySelectorAll`, `closest`, and `matches` for fast, declarative element lookups.

2

Layout Thrashing Prevention

Interleaving DOM reads (`offsetHeight`) and DOM writes (`style.height`) forces synchronous layout recalculation. Always batch reads first, then batch writes.

3

localStorage vs sessionStorage

`localStorage` persists across tabs and browser restarts (~5MB quota). `sessionStorage` is scoped to a single tab and cleared when the tab closes (~5MB quota).

4

Modern Observer APIs

`IntersectionObserver` efficiently checks when elements enter viewport (lazy loading). `ResizeObserver` detects element dimensions. `MutationObserver` watches DOM mutations.

💻 Interactive Code Walkthrough

Safe JSON LocalStorage wrapper and IntersectionObserver setup:

JAVASCRIPT
// Robust LocalStorage Wrapper with JSON Serialization
const storage = {
  get(key, fallback = null) {
    try {
      const item = localStorage.getItem(key);
      return item ? JSON.parse(item) : fallback;
    } catch {
      return fallback;
    }
  },
  set(key, value) {
    try {
      localStorage.setItem(key, JSON.stringify(value));
      return true;
    } catch (err) {
      console.error("Storage quota exceeded or disabled:", err);
      return false;
    }
  }
};

// Simulating browser storage usage
storage.set("theme_preference", { dark: true, accent: "emerald" });
console.log("Retrieved theme:", storage.get("theme_preference"));
Console Output:
CODE
Retrieved theme: { dark: true, accent: 'emerald' }
⚠️ Common Pitfalls & Interview Traps
Trap
Storing Sensitive Tokens in localStorage

The Risk: Storing JWTs or passwords in `localStorage` makes them accessible to any JavaScript script on the page, vulnerable to Cross-Site Scripting (XSS) attacks.

The Fix: Store sensitive authentication tokens in `HttpOnly`, `Secure`, `SameSite` cookies.

Trap
Synchronous Storage Blocking Main Thread

The Risk: Reading or writing huge JSON objects to `localStorage` blocks the main thread because Web Storage APIs are synchronous.

The Fix: Use `IndexedDB` (via libraries like `idb`) for large datasets or offline data caching.

⚡ 30-Second Quick Revision Cheat Sheet (TL;DR)
  • ✓ Web APIs are provided by the browser, not ECMAScript core.
  • ✓ `localStorage` persists indefinitely; `sessionStorage` is tab-scoped.
  • ✓ Both storage APIs are synchronous, string-only, and capped at ~5MB.
  • ✓ Avoid Layout Thrashing: Batch DOM style reads before DOM writes.
  • ✓ Use `IntersectionObserver` for high-performance image lazy loading and infinite scroll.

Finished this lesson?

Mark this chapter complete to update your learning streak and unlock the next lesson.