Curriculum / Advanced / Lesson 25

Local Storage

Persisting data in the browser with localStorage and sessionStorage.

25 of 30
advanced 📖 5 min read 🎯 3 questions

What is Web Storage?

Web Storage provides a way to store data locally in the browser. It's easier and more secure than cookies. There are two types:

💡 Key insight localStorage persists data even after the browser is closed. sessionStorage only persists for the current session.

localStorage vs sessionStorage

Basic Operations

// Store data
localStorage.setItem('key', 'value');

// Retrieve data
const value = localStorage.getItem('key');

// Remove data
localStorage.removeItem('key');

// Clear all data
localStorage.clear();

// Get number of stored items
const count = localStorage.length;

Storing Objects

Since localStorage only stores strings, you need to serialize objects with JSON.

// Store object
const user = { name: 'Alice', age: 25 };
localStorage.setItem('user', JSON.stringify(user));

// Retrieve object
const stored = JSON.parse(localStorage.getItem('user'));

Common Mistakes

Quick Quiz

1. How does localStorage differ from sessionStorage?

2. How do you store an object in localStorage?

3. Which method removes all data from localStorage?

Summary

Back to curriculum