Find a subject or note

13 results found

JavaScriptArray Methods, Loop Mechanics & The Async Trap

Mastering slice vs splice, search & reduce patterns, loop intent (for...in vs for...of vs map), and the async forEach trap.

JavaScriptasync / await & Modern Asynchronous Flow

Mastering async functions, the non-blocking await keyword, error handling with try/catch, and avoiding performance waterfalls.

JavaScriptcall(), apply(), bind() (Controlling this)

How to explicitly control function execution context in JavaScript using call, apply, and bind.

JavaScriptErrors, try/catch & Defensive Design

Understanding built-in error types, the Error object, custom error classes, async handling, and defensive validation patterns.

JavaScriptThe Event Loop

How JavaScript coordinates synchronous code, the Call Stack, Microtask Queue, and Macrotask Queue.

JavaScriptFetch API, HTTP & Web APIs

HTTP fundamentals, URLSearchParams, response handling, CORS, AbortController, and production service layers.

JavaScriptFirst-Class Functions, Callbacks & Closures

How first-class functions, callbacks, and closures connect to form the foundation of modern JavaScript.

JavaScriptObject Utilities (keys, values, entries, fromEntries)

How Object.keys, Object.values, Object.entries, and Object.fromEntries bridge objects and arrays in JavaScript.

JavaScriptPromises & Promise Combinators

Understanding asynchronous execution, Promise lifecycles, error propagation, and Promise combinators (all, allSettled, race, any).

JavaScriptReturn, Scope & Hoisting in Functions

How return statements, lexical scope, and hoisting determine how functions execute in JavaScript.

JavaScriptSecurity Basics: XSS & Safe DOM Rendering

Cross-Site Scripting (XSS) mechanics, safe DOM manipulation, innerHTML vs textContent, and the validation vs sanitization pipeline.

JavaScriptShallow vs. Deep Copy (Spread Pitfalls & JSON Limits)

Understanding object references, shallow copy pitfalls with spread, JSON limitations, and structuredClone.

JavaScriptWeb Storage: localStorage, sessionStorage & Cookies

Client-side storage mechanisms in JavaScript: comparing localStorage, sessionStorage, and Cookies for interview prep.

Web Storage: localStorage, sessionStorage & Cookies

Modern browsers provide client-side storage mechanisms to save data directly on the user's device without a database. Understanding how localStorage, sessionStorage, and Cookies differ in capacity, lifetime, and network behavior is a staple of front-end technical interviews.

All Web Storage systems store data as key/value string pairs only.

Web Storage architecture diagram comparing localStorage, sessionStorage, and Cookies
Web Storage (local & session) stays strictly inside the client, while Cookies travel over HTTP with every request.

1. localStorage

Part of the Browser Object Model (BOM), localStorage persists data with no expiration time. The data remains even after restarting the browser or computer.

  • Scope: Shared across all tabs and windows under the same origin (protocol://domain:port).
  • Best for: User UI theme (dark/light mode), saved shopping carts, offline cached data.
localstorage-crud.js
// 1. Store data (strings only)
localStorage.setItem("username", "Omar");
localStorage.setItem("theme", JSON.stringify({ mode: "dark" }));

// 2. Retrieve data
const user = localStorage.getItem("username"); // "Omar"
const theme = JSON.parse(localStorage.getItem("theme") || "{}");

// 3. Remove specific key
localStorage.removeItem("username");

// 4. Wipe all stored data for this origin
localStorage.clear();
Values must be strings; use JSON.stringify() and JSON.parse() for objects and arrays.

2. sessionStorage

sessionStorage shares the exact same API methods as localStorage, with one critical distinction:

  • Tab Lifetime: Data is stored only for the duration of the current page session. Closing the tab or window wipes the data completely.
  • Isolated Scope: Opening the same URL in a new tab creates a separate, independent session.
  • Best for: Multi-step checkout wizards, temporary draft inputs, one-time session flags.
sessionstorage-crud.js
// Stored only for the lifetime of this specific browser tab
sessionStorage.setItem("draftTitle", "Interview Notes");

console.log(sessionStorage.getItem("draftTitle")); // "Interview Notes"

sessionStorage.removeItem("draftTitle");
sessionStorage.clear(); // Clears current tab storage
Identical API to localStorage, but scoped strictly to the current browser tab.

3. Cookies

Cookies are small pieces of text (max 4KB) stored in the browser and automatically sent to the server with every HTTP request.

Key Attributes

  • expires=DATE or max-age=SECONDS: Sets expiration time (defaults to session cookie if omitted).
  • path=/: Restricts which URL paths send the cookie.
  • secure: Ensures transmission only over HTTPS connections.
  • HttpOnly: Prevents JavaScript from reading the cookie, defending against XSS attacks.
cookies-crud.js
// 1. Create a cookie with attributes
document.cookie = "username=Omar; max-age=3600; path=/; secure";

// 2. Read cookies (document.cookie returns all key=value pairs)
function getCookie(name) {
  const match = document.cookie
    .split("; ")
    .find(row => row.startsWith(name + "="));
  return match ? match.split("=")[1] : null;
}
console.log(getCookie("username")); // "Omar"

// 3. Delete a cookie (set expiration to a past date)
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
Cookies are read via document.cookie and deleted by setting an expiration date in the past.
localStorage vs. sessionStorage vs. Cookies Comparison

Feature

localStorage

sessionStorage

Cookies

Storage Limit

~5MB - 10MB per origin

~5MB per tab

~4KB per cookie

Lifetime

Persistent until explicitly deleted

Expires on tab/window close

Set by expires / max-age (or session)

Sent with HTTP?

No (client-side only)

No (client-side only)

Yes (automatically with every request)

Tab Scope

Shared across all tabs (same origin)

Isolated to current tab

Shared across all tabs (same origin/path)

Primary Purpose

Theme preference, offline caches, shopping cart

Multi-step form wizard, single-tab temp state

Auth session IDs, JWTs (HttpOnly), tracking

Think it throughInterview Question: Why shouldn't you store sensitive authentication tokens in localStorage?

localStorage is fully accessible to any client-side JavaScript code. If your web app has a Cross-Site Scripting (XSS) vulnerability, an attacker's injected script can run localStorage.getItem('token') and steal user sessions.

Storing authentication tokens in HttpOnly, Secure Cookies ensures the browser sends the token automatically with requests while completely hiding it from JavaScript, preventing XSS token theft.