Web Storage: Saving State

Web Storage: Saving State in JavaScript: Web Storage is like a Save File for your website. It allows you to store data directly in the user's browser so that…

Concept Explanation

Web Storage is like a Save File for your website. It allows you to store data directly in the user's browser so that when they refresh or come back tomorrow, their settings (like Dark Mode or items in a Cart) are still there.


Syntax or Core Structure

The Big Two

  1. LocalStorage: Stays forever (until the user clears it).
  2. SessionStorage: Wiped clean as soon as the tab is closed.
// 1. Saving Data
localStorage.setItem("theme", "dark");

// 2. Loading Data
const theme = localStorage.getItem("theme");

// 3. Deleting Data
localStorage.removeItem("theme");
localStorage.clear(); // Wipes EVERYTHING for this site

Potential Pitfalls

  1. String Only: LocalStorage can ONLY store strings. If you want to store an object or array, you MUST use JSON.stringify() to save it and JSON.parse() to read it.
  2. Size Limits: Most browsers limit you to about 5MB. Don't try to store high-res photos here!
  3. Security: Never store passwords or sensitive bank details in LocalStorage. Any script on your site (including hacked ones) can read it easily.

Best Practices

  • JSON is key: localStorage.setItem("user", JSON.stringify(userData));
  • Check Existence: Always check if getItem returns null before trying to use the value.
  • Performance: Reading from LocalStorage is fast, but writing thousands of times per second will lag your app.

Practice Exercises

  1. The Persistent Logger: Create a script that counts how many times the user has visited your page and displays it on screen.
  2. The Form Saver: Make a form that "Autosaves" what the user is typing into LocalStorage every 2 seconds.
  3. The Object Storage: Save a complex object (User with name, age, hobbies) and successfully read it back using JSON methods.