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
LocalStorage0%
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 IntermediateLocalStorage
SessionStorage

LocalStorage

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

The localStorage object provides a mechanism for storing key-value pairs in the user's web browser with no expiration date. Data persists even when the browser window is closed and reopened, making it ideal for persisting theme preferences, shopping cart state, and user settings.


1. Characteristics of LocalStorage

  • Persistence: Data remains stored indefinitely until cleared via JavaScript or user browser settings.
  • Storage Capacity: Approximately 5MB to 10MB per origin (depending on browser).
  • Domain Scoped (Same-Origin Policy): Data is isolated by protocol, domain, and port (https://example.com cannot access http://example.com or https://api.example.com).
  • Synchronous API: Methods execute on the main thread (blocking operations).
  • String Only: All keys and values are stored strictly as strings!

2. Core API Methods

1// 1. setItem(key, value): Stores a key-value pair
2localStorage.setItem('theme', 'dark');
3 
4// 2. getItem(key): Retrieves the value for a key (or returns null if non-existent)
5const activeTheme = localStorage.getItem('theme');
6console.log('Saved theme:', activeTheme); // 'dark'
7 
8// 3. removeItem(key): Deletes a specific key
9localStorage.removeItem('theme');
10 
11// 4. clear(): Wipes all stored keys for the current origin
12localStorage.clear();
13 
14// 5. length & key(index): Inspection
15console.log('Total items in storage:', localStorage.length);

3. Storing Objects & Arrays with JSON Serialization

Because localStorage only stores strings, attempting to pass a raw object results in "[object Object]":

1const user = { id: 1, name: 'Alex' };
2 
3// MISTAKE:
4localStorage.setItem('user', user);
5console.log(localStorage.getItem('user')); // "[object Object]" (Useless!)
6 
7// CORRECT WAY: Serialize with JSON
8localStorage.setItem('user', JSON.stringify(user));
9 
10// RETRIEVE: Deserialize with JSON.parse()
11const storedUser = JSON.parse(localStorage.getItem('user'));
12console.log(storedUser.name); // 'Alex'

4. Safe Storage Wrapper with try...catch

Accessing localStorage can throw errors if:

  1. 1
    The user has disabled cookies/storage in privacy settings.
  2. 2
    The browser is in strict private/incognito mode.
  3. 3
    The storage quota has been exceeded (QuotaExceededError).
1const StorageService = {
2 set(key, value) {
3 try {
4 const serialized = JSON.stringify(value);
5 localStorage.setItem(key, serialized);
6 return true;
7 } catch (error) {
8 console.error(`Storage quota exceeded or disabled for key "${key}":`, error);
9 return false;
10 }
11 },
12 
13 get(key, defaultValue = null) {
14 try {
15 const item = localStorage.getItem(key);
16 return item ? JSON.parse(item) : defaultValue;
17 } catch {
18 return defaultValue;
19 }
20 }
21};

5. Listening to Storage Changes Across Tabs: The storage Event

When localStorage is updated in one browser tab, other open tabs on the same origin receive a storage event:

1window.addEventListener('storage', (event) => {
2 console.log(`Key changed: ${event.key}`);
3 console.log(`Old Value: ${event.oldValue}`);
4 console.log(`New Value: ${event.newValue}`);
5 console.log(`Triggered by URL: ${event.url}`);
6 
7 if (event.key === 'theme') {
8 document.body.className = event.newValue;
9 }
10});

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
How long does data saved in localStorage persist?
Question 2
What data type does localStorage store for values?
Question 3
What happens if you call localStorage.getItem('non_existent_key')?
Question 4
Why must objects be passed through JSON.stringify() before saving to localStorage?
Question 5
In what scenario will the window storage event fire?
Next Lesson

SessionStorage

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

Related Lessons

Previous LessonNext Lesson
Organizing Code with ModulesSessionStorage

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