JavaScript - localStorage & sessionStorage
Overview
Estimated time: 15–20 minutes
localStorage
and sessionStorage
provide simple key-value storage in the browser for persisting data on the client side.
Learning Objectives
- Store and retrieve data using
localStorage
andsessionStorage
. - Understand the differences between the two storage types.
Prerequisites
localStorage Example
localStorage.setItem('username', 'alice');
console.log(localStorage.getItem('username'));
localStorage.removeItem('username');
sessionStorage Example
sessionStorage.setItem('token', 'abc123');
console.log(sessionStorage.getItem('token'));
sessionStorage.clear();
Common Pitfalls
- Storage is limited (usually 5–10MB per origin).
- Only strings can be stored (use
JSON.stringify
for objects).
Summary
Use localStorage and sessionStorage for simple, persistent client-side data storage.