JavaScript: Step 12- Browser Storage (localStorage/sessionStorage)

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:

localStoragesessionStorage
Data storedWithout expiration dateFor a single session or tab
Data deletedExplicitly by user or website/applicationWhen 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:

  1. 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"
  1. 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"
  1. Removing data from localStorage:
localStorage.removeItem('name');
  1. 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.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.