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
Syntax Structure
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
// 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
Expected Output
Real-World Application
Used across education platforms to remember the student's last visited lesson and dark mode setting.
Common Mistakes to Avoid
Quick Practice Challenge
Save your favorite programming language into `localStorage` under key 'favorite_lang' and retrieve it in the console.