Browser storage refers to the ability of web browsers to store data locally on the user’s device. There are two types of browser storage in JavaScript: localStorage and sessionStorage.
localStorage:
localStorage stores data without an expiration date, meaning the data will persist even after the browser window is closed. The data will only be deleted when it is explicitly removed by the user or by the website/application that created it.
sessionStorage:
sessionStorage stores data for a single session or tab. The data will be deleted when the user closes the tab or window, or when the browser is closed.
Tabular Comparisons:
localStorage | sessionStorage | |
---|---|---|
Data stored | Without expiration date | For a single session or tab |
Data deleted | Explicitly by user or website/application | When user closes tab or window, or when browser is closed |
Text Diagram:
Browser Storage
|
localStorage sessionStorage
| |
Data without Data for a single
expiration date session or tab
| |
Explicitly deleted Deleted when user
by user or website closes tab or window,
or when browser or when browser is closed
is closed |
|
Basic Programs:
- Storing and retrieving data using localStorage:
// Store data
localStorage.setItem('name', 'John Doe');
// Retrieve data
const name = localStorage.getItem('name');
console.log(name); // "John Doe"
- Storing and retrieving data using sessionStorage:
// Store data
sessionStorage.setItem('name', 'John Doe');
// Retrieve data
const name = sessionStorage.getItem('name');
console.log(name); // "John Doe"
- Removing data from localStorage:
localStorage.removeItem('name');
- Removing all data from localStorage:
localStorage.clear();
To run these programs in Visual Studio Code, create a JavaScript file with a .js
extension and use a web browser to open an HTML file that references the JavaScript file. For example:
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<title>Browser Storage Example</title>
</head>
<body>
<script src="script.js"></script>
</body>
</html>
// script.js
localStorage.setItem('name', 'John Doe');
const name = localStorage.getItem('name');
console.log(name); // "John Doe"
Open the index.html
file in a web browser to see the output in the console. Note that the output will only be visible in the web browser’s developer console, not in Visual Studio Code.