JavaScript Web Storage

1. What is Web Storage?

Web Storage API provides a way for browsers to store key/value pairs locally within the user's browser. It is more intuitive and secure than cookies for storing large amounts of data.

There are two main types of Web Storage:

2. Local Storage

Use localStorage when you want to save data permanently (e.g., user theme preference, saved cart items).

// 1. Set Item
localStorage.setItem("username", "Ragini");

// 2. Get Item
const name = localStorage.getItem("username");
document.write("Stored Name:", name);

// 3. Remove Item
localStorage.removeItem("username");

// 4. Clear All
localStorage.clear();
        
Output will appear here...

3. Session Storage

Use sessionStorage when you want to save data temporarily for a single session (e.g., form data while navigating between pages).

// 1. Set Item
sessionStorage.setItem("theme", "dark");

// 2. Get Item
const theme = sessionStorage.getItem("theme");
document.write("Current Theme:", theme);

/* 
   Note: If you close this tab and run this code again 
   without setting the item, it will return null.
*/
        
Output will appear here...

4. Storing Objects (JSON)

Web Storage can only store strings. To store arrays or objects, you must convert them to a string using JSON.stringify() and parse them back using JSON.parse().

const user = { name: "Ravi", age: 25, city: "Delhi" };

// Convert object to string and store
localStorage.setItem("user", JSON.stringify(user));

// Retrieve string and convert back to object
const storedUser = JSON.parse(localStorage.getItem("user"));

document.write(storedUser.name); // "Ravi"
document.write(storedUser.city); // "Delhi"
        
Output will appear here...

5. Interactive Demo

Try saving a value, then refresh the page. Local Storage data will remain, but Session Storage data will disappear if you close the tab.

6. Comparison Table

Feature Local Storage Session Storage
Lifetime Permanent (until manually cleared) Temporary (until tab closed)
Scope Shared across all tabs/windows Accessible only in the current tab
Capacity ~5-10 MB ~5 MB
Security Tip: Never store sensitive data like passwords, API keys, or credit card details in Local or Session Storage, as it is accessible by any script running on the page (XSS attacks).

Practice Questions

Test your understanding of Web Storage.

Easy

Q1: Save an item to Local Storage.

  • Use the localStorage object.
  • Save a key named username with the value "John Doe".
Easy

Q2: Retrieve an item from Session Storage.

  • Use the sessionStorage object.
  • Retrieve the value associated with the key theme.
  • Log the retrieved value to the console.
Medium

Q3: Remove and clear items from Local Storage.

  • Write the code to remove a single item with the key token.
  • Write the code to clear all data from localStorage.
Medium

Q4: Store a JavaScript object.

  • Given an object: let settings = { volume: 80, isMuted: false };
  • Convert the object into a JSON string.
  • Store the string in localStorage under the key settings.
Hard

Q5: Retrieve and parse a JSON object.

  • Write a function getSavedSettings().
  • Retrieve the settings string from localStorage.
  • If it exists, parse it back into an object and return it.
  • If it doesn't exist, return null.

Answer

Code: