ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

JavaScript Tutorial• 4 min read

Web Storage: LocalStorage & SessionStorage

Persisting user state and data on the client device

With Web Storage, web applications can store data locally within the user's browser with no expiration date (unlike cookies which have size limits and expire).

localStorage in Practice

localStorage.setItem("key", "value"): Stores an item.

localStorage.getItem("key"): Retrieves an item.

localStorage.removeItem("key"): Removes a single item.

JSON.stringify() and JSON.parse(): Enables saving complex objects and arrays into localStorage strings.

Saving and Retrieving State
// Saving complex data
const userSession = {
  theme: "dark",
  lastLesson: "javascript/async-await",
  completedCount: 14
};

localStorage.setItem("codexia_session", JSON.stringify(userSession));

// Retrieving data
const stored = localStorage.getItem("codexia_session");
if (stored) {
  const parsed = JSON.parse(stored);
  console.log("Welcome back! Active theme:", parsed.theme);
}
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

Which method converts a JavaScript object into a JSON string suitable for localStorage?