Lecture Notes Of Day 16Local Storage and Session Storage
Objective:
The goal
of today's lesson is to understand how to use web storage in JavaScript to save
data locally in the user's browser. We'll explore localStorage and
sessionStorage, their differences, how to store and retrieve data, and how to
remove items from storage.
Topics
Covered:
1. localStorage
vs sessionStorage
2. Storing
and Retrieving Data
3. Removing
Items from Storage
1.
localStorage vs sessionStorage
Both
localStorage and sessionStorage are used to store data on the client-side in a
user's browser. However, they have distinct behaviors regarding persistence and
lifespan:
localStorage:
- Persistence:
Data stored in localStorage persists even when the browser is closed and
reopened. The data is retained until explicitly removed by the user or by
code (e.g., using removeItem() or clear()).
- Scope:
Data is accessible across all tabs and windows of the same origin (same
domain, protocol, and port).
- Use
Case: Ideal for storing data that you want to keep
even after the user leaves and returns to the website, such as user
preferences or themes.
Example:
localStorage.setItem('username', 'JohnDoe');
let username = localStorage.getItem('username');
console.log(username); // Outputs: JohnDoe
sessionStorage:
- Persistence:
Data stored in sessionStorage only lasts for the duration of the page
session. A session is defined as the period between opening a browser tab and
closing it. Once the tab is closed, the data is lost.
- Scope:
Data is only available within the same tab or window. It is not shared
between tabs or windows, even if they are opened from the same origin.
- Use
Case: Ideal for storing data that should only
persist for the duration of a single session, such as temporary form data
or session-specific information.
Example:
sessionStorage.setItem('sessionId', 'abc123');
let sessionId =
sessionStorage.getItem('sessionId');
console.log(sessionId); // Outputs: abc123
2.
Storing and Retrieving Data
Storing
Data:
You can
use localStorage.setItem() and sessionStorage.setItem() to store data. These
methods take two arguments:
- The
first argument is the key (a string representing the name of the
item).
- The
second argument is the value (a string representing the data you
want to store).
If the
value is not a string, it will be automatically converted to a string using
String(value).
Example
of Storing Data:
// Storing data in localStorage
localStorage.setItem('username', 'JaneDoe');
// Storing data in sessionStorage
sessionStorage.setItem('sessionId', 'xyz789');
Retrieving
Data:
You can
use localStorage.getItem() and sessionStorage.getItem() to retrieve data. These
methods take one argument — the key — and return the corresponding
value.
Example
of Retrieving Data:
// Retrieving data from localStorage
let username = localStorage.getItem('username');
console.log(username); // Outputs: JaneDoe
// Retrieving data from sessionStorage
let sessionId =
sessionStorage.getItem('sessionId');
console.log(sessionId); // Outputs: xyz789
If the
specified key does not exist in the storage, both methods will return null.
Storing
and Retrieving Objects:
You
cannot directly store objects in localStorage or sessionStorage because both
can only store strings. However, you can use JSON.stringify() to convert an
object to a string before storing it and JSON.parse() to convert it back to an
object when retrieving it.
Example
of Storing and Retrieving Objects:
// Creating an object
const user = {
name: 'John
Doe',
age: 30
};
// Storing the object
localStorage.setItem('user', JSON.stringify(user));
// Retrieving and parsing the object
let storedUser =
JSON.parse(localStorage.getItem('user'));
console.log(storedUser); // Outputs: { name: 'John Doe', age: 30 }
3.
Removing Items from Storage
Removing
Specific Items:
To remove
a specific item from storage, you can use localStorage.removeItem() or
sessionStorage.removeItem(). You need to pass the key of the item you
want to remove.
Example
of Removing a Specific Item:
// Removing a specific item from localStorage
localStorage.removeItem('username');
// Removing a specific item from sessionStorage
sessionStorage.removeItem('sessionId');
Clearing All Items:
To remove
all items from localStorage or sessionStorage, you can use localStorage.clear()
or sessionStorage.clear(). This will remove all data stored in the respective
storage.
Example of Clearing All Items:
// Clearing all data from localStorage
localStorage.clear();
// Clearing all data from sessionStorage
sessionStorage.clear();
Summary
of Key Differences:
|
Feature |
localStorage |
sessionStorage |
|
Lifetime |
Persists
until manually removed |
Data is
cleared when the tab is closed |
|
Scope |
Available
across all tabs/windows |
Only
available in the same tab/window |
|
Use
Case |
Storing
long-term data (e.g., user preferences) |
Storing
temporary data (e.g., session-specific data) |
|
Storage
Capacity |
Typically
5-10MB depending on the browser |
Typically
5-10MB depending on the browser |
Practice Problems:
1. Problem 1: Store
the user's email address in localStorage and retrieve it to display on the
console.
2. Problem 2: Create
a session where a user logs in. Store the session token in sessionStorage and
show how to retrieve and display it on the console.
3. Problem 3: Store
an array of numbers in localStorage. First, convert it to a string using
JSON.stringify(), and then retrieve it, parse it back into an array, and
display it in the console.
4. Problem 4: Create
a form with a text input for the user's name. After submitting, store the name
in localStorage. When the page is refreshed, retrieve the name and display it
in the input field.
Conclusion:
In this lesson, we learned how to use localStorage and sessionStorage to store data in the user's browser. We explored the differences between the two types of storage, how to store and retrieve data, and how to remove items from storage. These tools are invaluable for creating more dynamic web applications that remember user data between page loads or sessions.
