1. What is the Web Storage API?
Before HTML5, web applications stored client-side data exclusively in HTTP cookies. The Web Storage API provides a much larger (up to 5-10MB), secure, and performance-friendly mechanism to store key-value string data directly in the browser without transmitting it with every HTTP request.
2. localStorage vs sessionStorage
| Feature | localStorage |
sessionStorage |
|---|---|---|
| Persistence | Persists indefinitely until cleared by user or script. | Cleared automatically when the browser tab is closed. |
| Scope | Shared across all tabs/windows of the same domain origin. | Isolated to the specific individual browser tab. |
| Best For | User theme preferences, auth tokens, cached questions. | Active test session answers, temporary scratchpad notes. |
3. Web Storage API Methods
// 1. Storing data (strings only)
localStorage.setItem("cbt_student_name", "Ankit Sharma");
// Storing objects by serializing with JSON.stringify()
const preferences = { theme: "dark", fontSize: 16 };
localStorage.setItem("cbt_prefs", JSON.stringify(preferences));
// 2. Retrieving data
const student = localStorage.getItem("cbt_student_name");
const parsedPrefs = JSON.parse(localStorage.getItem("cbt_prefs"));
// 3. Removing items & clearing
localStorage.removeItem("cbt_student_name");
localStorage.clear(); // Clears all keys for current origin