Imagine you are attempting a 30-question mock CBSE Informatics Practices quiz on a school website. You have answered 22 questions when your little brother snatches your phone to take a call, or your laptop's Wi-Fi drops for a second and the page reloads. When you get back to the quiz, are your 22 answers still there, or is the form blank again, forcing you to start from question 1?
The honest answer is: it depends entirely on whether the website's developer used client-side storage. If they did nothing special, your answers vanish the instant the page reloads, because a web page's JavaScript variables live only in the browser's working memory for that single page load — the moment the page is replaced or refreshed, every variable is wiped clean. This chapter is about the two browser features built specifically to fix this problem: localStorage and sessionStorage, together called the Web Storage API.
The Problem: Browsers Forget Everything by Default
To understand why Web Storage exists, you first need to understand what the web forgets. HTTP, the protocol that browsers use to ask servers for pages, is stateless — every request a browser sends is treated by the server as if it has no memory of any previous request. When you click a link, load a new page, or refresh, the browser essentially starts over: it discards the old page's JavaScript variables and loads a fresh copy of the page's HTML, CSS and JavaScript.
This is not a bug — it is how the web was designed to scale to billions of independent page loads. But it creates real problems for real applications. A shopping cart on an e-commerce site needs to remember what you added even if you navigate to a different product page. A quiz app needs to remember your partial answers if you accidentally refresh. A settings page needs to remember that you switched to dark mode, so it does not reset to light mode every time you open a new tab.
Before 2009, the only real tool web developers had for this was the cookie — a small piece of text (roughly 4 KB) that the browser stores and automatically attaches to every single HTTP request sent to that website's server. Cookies work, but they were never designed for storing meaningful amounts of application data: they are small, and because they travel with every request, a page with many cookies makes every single network request larger and slower — including requests for images and stylesheets that have nothing to do with the cookie's data. The Web Storage API, standardized as part of HTML5, was introduced specifically to give web pages a much larger, purely client-side place to keep data — one that is never sent to the server automatically.
Two Notebooks: The Core Idea Before the Code
Before looking at any code, picture two different notebooks a student might keep during an exam.
The first is a rough sheet for one exam sitting. You scribble workings on it during the three-hour paper. The moment the invigilator says "time up" and collects the papers, that rough sheet is thrown away — it has no value once the sitting ends, and you would never expect it to still exist next week.
The second is your personal formula notebook that you carry home, keep in your bag, and bring back for every future exam until you deliberately throw it out or lose the bag. It survives across exam sittings — you close it after Monday's test and reopen the very same notebook on Wednesday.
sessionStorage behaves like the rough sheet: it belongs to one browser tab, for as long as that tab (that "sitting") stays open, and disappears the instant the tab is closed. localStorage behaves like the formula notebook: it belongs to the website (technically, the "origin" — more on that shortly) and survives even after you close the browser entirely and reopen it days later.
Meet the Web Storage API
Both localStorage and sessionStorage are objects that JavaScript running in a browser can access directly — no library, no server, no setup. Both implement the exact same four core methods, so once you learn one, you have learned both:
localStorage.setItem("key", "value"); // save data
localStorage.getItem("key"); // read data -> returns "value" or null
localStorage.removeItem("key"); // delete one entry
localStorage.clear(); // delete everything for this origin
Replace every localStorage above with sessionStorage and the code works identically — the only difference is how long the data survives and who else can see it, which we will pin down precisely in a moment.
A crucial, easy-to-miss fact: every key and every value stored by the Web Storage API is a string. There is no separate storage for numbers, booleans, or objects — if you hand it something that is not already a string, JavaScript silently converts it to one using its default string conversion, which is rarely what you want.
localStorage.setItem("score", 18);
console.log(typeof localStorage.getItem("score"));
// "string" -- NOT "number", even though we stored 18
console.log(localStorage.getItem("score") === 18);
// false -- "18" (string) is not === 18 (number)
console.log(localStorage.getItem("score") === "18");
// true
This single fact trips up more beginner programmers than almost anything else in this chapter, so trace through it carefully: setItem stored the number 18, but the moment it was written into storage it became the three-character string "18". If your quiz app later does if (localStorage.getItem("score") > 15), that comparison still happens to work here because JavaScript converts the string back to a number for a > comparison — but relying on that is fragile and a common source of bugs once the values get more complex, like arrays or objects.
Worked Example: Saving and Reading Data
Let's trace a small, realistic example line by line — a "remember my name" feature on a school portal's login page.
// Line 1: user typed "Ananya" and clicked "Remember me"
localStorage.setItem("studentName", "Ananya");
// Line 2: page reloads (simulating tomorrow's visit)
// ... browser reloads the page entirely, all JS variables reset ...
// Line 3: on the new page load, we check storage
const savedName = localStorage.getItem("studentName");
console.log(savedName); // "Ananya"
if (savedName !== null) {
console.log("Welcome back, " + savedName + "!");
} else {
console.log("Please log in.");
}
// Output: "Welcome back, Ananya!"
Trace it: Line 1 writes the pair ("studentName", "Ananya") to the browser's on-disk storage for this website's origin — not to a JavaScript variable, which would have died on reload. When the page reloads (Line 2), every ordinary variable is gone, but the Web Storage data is untouched, because it lives outside the page's memory, managed by the browser itself. Line 3 reads it back successfully. Notice the explicit check savedName !== null: getItem returns the special value null (not an empty string, not undefined) when the key does not exist — checking for this correctly is what lets the code distinguish "never saved anything" from "saved an empty string."
Storing More Than Text: Objects via JSON
Real applications rarely need to store a single string — a student's quiz progress, for instance, is naturally an object with several fields. Since Web Storage only accepts strings, the standard technique is to convert a JavaScript object into a JSON string before saving it, and convert it back after reading it.
const quizProgress = {
studentName: "Rohan",
currentQuestion: 22,
answers: [1, 3, 2, 4, 1],
startedAt: "2026-08-13T10:05:00"
};
// Save: object -> JSON string
sessionStorage.setItem("quizProgress", JSON.stringify(quizProgress));
// ... phone call interrupts, page accidentally reloads ...
// Restore: JSON string -> object
const raw = sessionStorage.getItem("quizProgress");
const restored = raw ? JSON.parse(raw) : null;
if (restored) {
console.log("Resuming from question " + restored.currentQuestion);
// Output: "Resuming from question 22"
}
JSON.stringify() walks the object and produces the text {"studentName":"Rohan","currentQuestion":22,"answers":[1,3,2,4,1],"startedAt":"2026-08-13T10:05:00"} — this is what actually gets written to storage. JSON.parse() does the reverse, rebuilding a real JavaScript object with a working .currentQuestion property from that text. This stringify-before-saving, parse-after-reading pattern is used constantly in real front-end code, so it is worth committing to memory as a pair, not two unrelated functions.
sessionStorage vs. localStorage vs. Cookies — Precisely
These three tools are often confused because they superficially "all store small pieces of data in the browser," but they differ in ways that matter a great deal once you build anything real.
- Lifetime.
sessionStoragedies the moment its tab closes.localStoragesurvives closing the browser and even restarting the computer — it is only removed if the user clears browsing data, the page's script explicitly deletes it, or the browser enforces storage limits. A cookie's lifetime is set explicitly by the developer (it can be made to expire in one hour, one year, or "at end of session" like sessionStorage). - Scope.
localStorageis shared by every tab and window that is open to the same origin (same protocol + domain + port).sessionStoragebelongs to one single tab only — opening the same website in a second tab gives that second tab a completely separate, empty sessionStorage, even though it is the exact same website. - Sent to the server? Neither
localStoragenorsessionStorageis ever sent to a server automatically — reading them requires JavaScript to explicitly do so, for example inside a fetch request. Cookies, in contrast, are attached automatically by the browser to every matching HTTP request, which is precisely why login sessions have traditionally been built with cookies. - Capacity. A single cookie is limited to roughly 4 KB, and the total set of cookies for a domain is capped similarly low. Both
localStorageandsessionStoragetypically allow around 5 MB of text per origin in most desktop browsers — over a thousand times more room than cookies, though the exact figure is not part of any standard and varies by browser.
The Cross-Tab Misconception (Corrected)
Here is a mistake that even students who have used localStorage before commonly make: assuming sessionStorage behaves like localStorage but "just for a shorter time." It does not — the two differ in scope, not only in lifetime, and that distinction is the more important one to get right.
Suppose a shopping website keeps track of which step of checkout a shopper is on using sessionStorage.setItem("cartStep", "2"). If that same shopper — perhaps comparing prices — opens the identical website in a second tab, that second tab does not see cartStep as "2". It sees nothing at all, because sessionStorage is scoped to the individual browsing tab, not to the website. Each tab, even to the very same URL, gets its own private sessionStorage that no other tab — not even a tab that is a duplicate of the first — can read (a tab opened via "duplicate tab" does inherit a one-time copy at the moment of duplication, but the two immediately diverge afterward and never sync again).
localStorage, on the other hand, genuinely is shared. If that same website instead saves the shopper's chosen currency with localStorage.setItem("currency", "INR") in Tab A, then switching to Tab B and running localStorage.getItem("currency") returns "INR" immediately — both tabs are reading and writing the exact same storage bucket, because it belongs to the origin, not to any one tab. The diagram below makes this concrete.
A second misconception worth correcting directly: many students assume localStorage "syncs across a student's devices," the way a Google account or a cloud-saved document does. It does not. localStorage is tied to one specific combination of browser software and physical device (more precisely, to one browser profile on one device). Data saved on your school computer's Chrome will not appear when you open the same website on your phone, or even in a different browser on the same computer — because there is no server involved at all; it is purely a file the browser keeps on that one machine's disk. It also is not encrypted — anyone with access to that browser profile (or its files on disk) can read it in plain text, which matters for the security discussion below.
Storage Limits and What Happens When You Exceed Them
Because Web Storage is generous (commonly around 5 MB per origin) but not unlimited, well-written applications handle the case where storage is full. Attempting to save data that would exceed the quota does not silently fail — it throws a DOMException, which good code catches:
try {
localStorage.setItem("hugeLog", veryLongString);
} catch (err) {
if (err.name === "QuotaExceededError") {
console.log("Storage full — cannot save more data.");
}
}
This matters practically: a badly designed quiz app that appends every keystroke to a growing log in localStorage without ever clearing it could, after weeks of use, hit this limit and start throwing errors on every save — silently breaking the "remember my progress" feature it was built for. Calling removeItem or clear once data is no longer needed (for instance, once a quiz is finally submitted) is part of writing this code correctly, not an optional nicety.
Reacting to Changes: the storage Event
Because localStorage is shared across tabs, the browser provides a way for one tab to be notified when another tab changes it — the storage event. This is genuinely useful: imagine a student has a school portal open in two tabs and logs out in one; the other tab can detect this and also show the logged-out state.
window.addEventListener("storage", function (event) {
console.log("Key changed:", event.key);
console.log("Old value:", event.oldValue);
console.log("New value:", event.newValue);
});
There is one detail here that surprises almost everyone the first time: this event fires in every other tab of the same origin except the tab that made the change. The tab that actually called setItem never receives its own storage event — only the other, listening tabs do. This makes sense once you think about what the event is for: a tab already knows what it just did; the event exists purely to inform tabs that would otherwise have no way of knowing.
Where Client-Side Storage Should Not Be Used
Because localStorage is plain, unencrypted text sitting on the user's disk, and because any JavaScript running on the page — including malicious script injected through a security flaw called cross-site scripting (XSS) — can read all of it, there is one firm rule: never store passwords, bank details, Aadhaar or other identity numbers, or long-lived authentication tokens in localStorage or sessionStorage. A genuine login system's sensitive session token is generally better kept in a cookie marked HttpOnly, which JavaScript cannot read at all, precisely to block this class of attack. Web Storage is the right tool for convenience data that would not cause real harm if read by an attacker — a theme preference, an unfinished quiz's answers, a shopping cart's contents, the last search filter used — not for anything that, if leaked, could be misused.
Why This Matters for CBSE and Beyond
The CBSE Class 9–10 Computer Applications and Class 11–12 Informatics Practices syllabi build toward genuine web development skills, and any project component involving a browser-based form, quiz, or small app is exactly where this API is used in practice — not as a theoretical add-on, but as the standard, spec-defined way JavaScript keeps data between page loads without a server. Understanding precisely which storage survives what, and why, is also the kind of conceptual question — "does sessionStorage persist across tabs?", "what type are the values stored?" — that appears directly in board exam short-answer questions on Web APIs.
Active Recall
- A student writes
localStorage.setItem("marks", 95)and later runslocalStorage.getItem("marks") === 95. Will this betrueorfalse? Explain precisely why, referring to what type Web Storage actually stores. - A website is open in two tabs. Tab 1 runs
sessionStorage.setItem("step", "3"). What doessessionStorage.getItem("step")return in Tab 2? What wouldlocalStorage.getItem("step")return in Tab 2 if Tab 1 had usedlocalStorageinstead? - Why does the
storageevent never fire in the same tab that made the change? What problem would it cause if it did? - A developer wants to save a logged-in user's authentication token so their site "remembers" them. Explain why storing this token in
localStorageis a security risk, and name a safer alternative mentioned in this chapter. - Write one line of code that safely reads a JSON object named
"settings"back out oflocalStorage, handling the case where nothing has been saved yet (sogetItemreturnsnull).
Summary
- HTTP is stateless and ordinary JavaScript variables are wiped on every page reload; the Web Storage API (
localStorageandsessionStorage) exists to let a web page keep data on the client between reloads without a server. sessionStorageis scoped to one browser tab and is erased when that tab closes;localStorageis scoped to the origin (website), is shared across every tab of that origin, and survives closing and reopening the browser.- Both use the identical four-method API:
setItem,getItem,removeItem,clear— everything stored is a string, so objects must be converted withJSON.stringifybefore saving and rebuilt withJSON.parseafter reading. - Unlike cookies, neither storage is ever sent to a server automatically, and both offer roughly a thousand times more capacity than a cookie (commonly around 5 MB per origin, though this is not standardized).
- Exceeding the storage quota throws a catchable
QuotaExceededErrorrather than failing silently. - The
storageevent notifies other tabs of the same origin — never the tab that made the change — whenlocalStoragechanges. - Because the data is unencrypted and readable by any script on the page, sensitive information such as passwords or authentication tokens must never be stored here.