Lesson 51 - Introduction to Browser Storage
What is Browser Storage?
Browser storage allows web applications to store data on a user's browser. JavaScript provides two main types of storage:
- localStorage – Stores data with no expiration. Data remains even after the browser is closed.
- sessionStorage – Stores data for the duration of a page session. Data is lost when the page is closed.
Why Use Browser Storage?
- Saves user preferences.
- Stores temporary data for faster page loading.
- Reduces reliance on server-side storage.
The Difference Between localStorage and sessionStorage
Feature | localStorage | sessionStorage |
---|---|---|
Data Lifespan | Permanent (until manually cleared) | Session-based (deleted when the page is closed) |
Scope | Accessible across multiple tabs/windows of the same origin | Available only within the same tab |
Size Limit | ~5MB per domain | ~5MB per domain |
Use Case | Storing user preferences, theme settings, authentication tokens | Storing temporary form data, cart items for session |
Accessing Browser Storage
Browser storage is accessible via the window
object.
// Access localStorage and sessionStorage
console.log(window.localStorage);
console.log(window.sessionStorage);
Summary
- localStorage keeps data until it's manually deleted.
- sessionStorage keeps data only for the current session.
- Both store key-value pairs and can be accessed via JavaScript.
In the next lesson, we will learn how to store, retrieve, and remove data using localStorage
and sessionStorage
.
Try Your Hand
- Open your browser's Developer Console (
F12
orCtrl+Shift+I
-> Console tab). - Type
window.localStorage
andwindow.sessionStorage
to explore the stored data. - Experiment with adding, retrieving, and deleting values.
Stay tuned for Day 52, where we will explore storing and retrieving data with localStorage!