JavaScript Web Storage: LocalStorage, SessionStorage & Client-Side Cookies

Modern web applications frequently need to store user state locally on the client machine—such as UI dark/light themes, authentication tokens, shopping cart items, and draft form entries. HTML5 introduced the Web Storage API (LocalStorage and SessionStorage) to replace the ancient, 4KB-limited HTTP cookie mechanism.

Browser Client-Side Storage Mechanisms Comparison

Figure 8: Side-by-side comparison of LocalStorage, SessionStorage, Cookies, and IndexedDB storage quotas and lifetimes.

Using window.localStorage (Permanent Storage)

// 1. Storing primitive data
localStorage.setItem("themePreference", "dark");

// 2. Storing Objects / Arrays (Requires JSON.stringify)
const userSession = {
    username: "vikram99",
    role: "student",
    lastLogin: Date.now()
};
localStorage.setItem("currentUser", JSON.stringify(userSession));

// 3. Retrieving and Deserializing data
const rawData = localStorage.getItem("currentUser");
if (rawData) {
    const user = JSON.parse(rawData);
    console.log("Welcome back,", user.username);
}

// 4. Removing items and Clearing
localStorage.removeItem("themePreference");
// localStorage.clear(); // Clears all keys for current origin!

Using window.sessionStorage (Tab Session Storage)

Has identical API methods (setItem, getItem, removeItem), but all data is discarded the moment the user closes the browser tab. Perfect for multi-step form wizards!

University Exam Corner (BCA / MCA Notes)

Exam Question: "Compare Cookies and LocalStorage on capacity, lifetime, and network overhead."

PropertyHTTP CookiesLocalStorage
Capacity Limit~4 Kilobytes (Tiny)~5 to 10 Megabytes
Network OverheadSent with EVERY HTTP request headerNever transmitted to server automatically
ExpirationSet by server/client Max-AgePermanent until cleared explicitly

Next Step

How do you delay execution or run periodic background loops? Proceed to: JavaScript Timers: setTimeout & setInterval →

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!