Special Offer Diwali Special Bundle Offer: 3 courses for ₹8,999, save ₹9,001 (50% OFF)! Limited seats available. View Bundles →
0% Completed
Tutorials / JavaScript Tutorial / Chapter 5: Asynchronous JavaScript & Modern APIs
JAVASCRIPT ⏱ 10 min read

Local Storage & Session Storage

Web Storage APIs allow web applications to store key-value data directly inside the user's browser across page visits.

What is it?

`localStorage` and `sessionStorage` are browser storage mechanisms. `localStorage` persists indefinitely even after the browser is closed and reopened, while `sessionStorage` clears when the browser tab closes.

Why is it used?

Stores user theme preferences (Light/Dark mode), shopping cart items for guest visitors, recently viewed lessons, and form drafts.

Detailed Explanation

Web Storage Methods: • `localStorage.setItem('key', 'value')`: Stores value. • `localStorage.getItem('key')`: Retrieves value (returns `null` if missing). • `localStorage.removeItem('key')`: Deletes key. • `localStorage.clear()`: Wipes all data for the domain. Storing Objects: Web Storage only stores strings! To store objects or arrays, serialize with `JSON.stringify()` on save, and deserialize with `JSON.parse()` on retrieval.

Syntax Structure

Syntax Blueprint
localStorage.setItem('igm_theme', 'dark');
const theme = localStorage.getItem('igm_theme');
localStorage.setItem('user', JSON.stringify({ name: 'Ash' }));
const user = JSON.parse(localStorage.getItem('user'));

Code Example

JAVASCRIPT Code
// Course Bookmark Manager via LocalStorage (Guest & Offline Friendly)
const BookmarkManager = {
  STORAGE_KEY: "igm_bookmarked_lessons",

  getBookmarks() {
    const raw = localStorage.getItem(this.STORAGE_KEY);
    return raw ? JSON.parse(raw) : [];
  },

  addBookmark(lessonSlug, lessonTitle) {
    const bookmarks = this.getBookmarks();
    if (!bookmarks.some(b => b.slug === lessonSlug)) {
      bookmarks.push({ slug: lessonSlug, title: lessonTitle, date: new Date().toISOString() });
      localStorage.setItem(this.STORAGE_KEY, JSON.stringify(bookmarks));
      console.log(`Bookmarked: ${lessonTitle}`);
    }
  },

  removeBookmark(lessonSlug) {
    const filtered = this.getBookmarks().filter(b => b.slug !== lessonSlug);
    localStorage.setItem(this.STORAGE_KEY, JSON.stringify(filtered));
  }
};

BookmarkManager.addBookmark("intro-python", "Introduction to Python");
console.log("Saved Bookmarks:", BookmarkManager.getBookmarks());

Explanation of the Code

• Encapsulates bookmarks in a clean utility object. • Uses `JSON.stringify` and `JSON.parse` to persist JavaScript arrays seamlessly in `localStorage`.

Expected Output

Bookmarked: Introduction to Python Saved Bookmarks: [ { slug: 'intro-python', title: 'Introduction to Python', date: '...' } ]

Real-World Application

Used across education platforms to remember the student's last visited lesson and dark mode setting.

Common Mistakes to Avoid

• Storing sensitive credentials (like passwords or private keys) in `localStorage` (it is vulnerable to XSS; use httpOnly cookies for sensitive auth tokens). • Forgetting that storing an object directly (`localStorage.setItem('key', obj)`) results in `"[object Object]"`.

Quick Practice Challenge

Save your favorite programming language into `localStorage` under key 'favorite_lang' and retrieve it in the console.

Key Takeaways

• `localStorage` persists across sessions; `sessionStorage` clears on tab close. • Only stores strings; use `JSON.stringify()` and `JSON.parse()` for objects. • Never store sensitive credentials or passwords in web storage.