Exploring Local and Session Storage in JavaScript
Tags: webdev, javascript, programming, beginners
Published: 2023-09-04 07:30:34

## Introduction
When working on web applications, you can store data locally in the user’s browser using the HTML5 Web Storage feature.

Web storage allows developers to store data, such as user preferences, session information etc., locally within the user’s browser. This improves user experience and reduces the need to repeatedly fetch data from the server.

The saved data stays in the browser and can not be transferred anywhere else. You can access and manipulate this data to enhance your web applications and create a smoother user experience.

Web storage has two main types local storage and session storage. In this blog post, you will learn about local storage and session storage in JavaScript.

## What are Local Storage and Session Storage?
Local Storage and Session Storage are types of web storage provided by modern web browsers to store data in the user’s browser. They both allow you to store data in the form of key-value pairs, that stay in the browser even after the user closes the browser tab or the entire browser session.

Now, you might be wondering that both storage options allow you to store data, but what sets them apart from each other?

So, let’s learn about local storage and session storage individually to gain a better understanding of each.

## Local Storage
Local Storage is a web storage option that allows you to store data in key-value pairs in a web browser with no expiration time. This means that data stored in Local Storage persists within the browser even after the user closes the browser tab, ends the entire browser session, or navigates away from the page.

To work with Local Storage, you can use the `localStorage` object in JavaScript. Here’s how you can store, access and remove data using Local Storage:

**Storing data item**
Syntax:

```
localStorage.setItem(key, value);
```
Here, ‘key’ is the name or identifier for the data item you want to store and ‘value’ is the value for that specified key.

Example:

```
// Storing data item in Local Storage
localStorage.setItem('firstName', 'Johan');
localStorage.setItem('lastName', 'Fortner');
localStorage.setItem('email', 'johan@example.com');
```
**Accessing data item**
Syntax:

```
localStorage.getItem(key);
```
Example:

```
// Accessing data item from Local Storage
const firstName = localStorage.getItem('firstName');
const lastName = localStorage.getItem('lastName');
const email= localStorage.getItem('email');

console.log(firstName); // Output: Johan
console.log(lastName); // Output: Fortner
console.log(email); // Output: johan@example.com
```
**Removing data item**
Syntax:

```
localStorage.removeItem(key);
```
Example:

```
// Removing data item from Local Storage
localStorage.removeItem('lastName');
```
**Removing all the local storage items**

```
localStorage.clear();
```

## Session Storage
Session Storage is similar to Local Storage, but it stores data only for the duration of a page session. That means when the user closes the tab or browser, data stored in Session Storage will be deleted.

To work with Session Storage, you can use the `sessionStorage` object in JavaScript. Here’s how you can store, access and remove data using Session Storage:

**Storing data item**
Syntax:

```
sessionStorage.setItem(key, value);
```
Here, ‘key’ is the name or identifier for the data item you want to store and ‘value’ is the value for that specified key.

Example:

```
// Storing data item in Session Storage
sessionStorage.setItem('firstName', 'Johan');
sessionStorage.setItem('lastName', 'Fortner');
sessionStorage.setItem('email', 'johan@example.com');
```
**Accessing data item**
Syntax:

```
sessionStorage.getItem(key);
```
Example:

```
// Accessing data item from Session Storage
const firstName = sessionStorage.getItem('firstName');
const lastName = sessionStorage.getItem('lastName');
const email= sessionStorage.getItem('email');

console.log(firstName); // Output: Johan
console.log(lastName); // Output: Fortner
console.log(email); // Output: johan@example.com
```
**Removing data item**
Syntax:

```
sessionStorage.removeItem(key);
```
Example:

```
// Removing data item from Session Storage
sessionStorage.removeItem('lastName');
```

**Removing all the session storage items**

```
sessionStorage.clear();
```

## Checking Browser Support for Local and Session Storage
Here’s how you can check browser support for local and session storage.

```
// Check for localStorage browser support
const localStorageSupported = typeof localStorage !== 'undefined';

// Check for sessionStorage browser support
const sessionStorageSupported = typeof sessionStorage !== 'undefined';

console.log(`localStorage supported: ${localStorageSupported}`);
console.log(`sessionStorage supported: ${sessionStorageSupported}`);
```
Here, `localStorageSupported` checks the type of `localStorage` and if the type of `localStorage` is not equal to ‘undefined’, then the value of this variable will be set to `true` which means the browser supports local storage. Otherwise, it is set to `false` which means the browser does not support local storage.

`sessionStorageSupported` checks the type of `sessionStorage` and if the type of `sessionStorage` is not equal to ‘undefined’, then the value of this variable will be set to `true` which means the browser supports session storage. Otherwise, it is set to `false` which means the browser does not support session storage.

## Differences Between Local Storage and Session Storage
Here are the key differences between local storage and session storage.

1. **Data Lifespan**: Data stored in local storage persists within the browser even after the user closes the browser tab, ends the entire browser session, or navigates away from the page. This is like long-term memory.
Data stored in session storage will be lost when the user closes the tab or browser. This is like short-term memory.

2. **Storage Capacity**: The capacity of Local Storage can range from 5 to 10 MB per domain, depending on the browser.
Session Storage also provides a similar storage capacity, but usually enough for temporary needs.

3. **Scope**: Data stored in Local Storage in one tab or window is accessible to scripts running in other tabs or windows of the same origin domain.
Data stored in Session Storage in one tab is not accessible to scripts running in other tabs or windows, even if they belong to the same domain.

4. **Use Cases**: Local Storage is used for storing data such as user preferences, cached data, remembering user login info etc.
Session Storage is used for storing data such as multi-page form progress, shopping cart, game states etc.

## Conclusion
In conclusion, web storage is a valuable feature that allows developers to store data locally within a user’s browser.

There are two main types of web storage: Local Storage and Session Storage. Local Storage stores data with no expiration time, making it persistent even after the user closes the browser or navigates away from the page. On the other hand, Session Storage is limited to the duration of a page session and deletes all the data when the user closes the tab or browser.

Both storage options are easy to work with using JavaScript, allowing you to store, access, and remove data in key-value pairs.

It’s important to check for browser support when using these storage options to ensure your web application behaves consistently across different browsers.

By understanding the key differences between Local Storage and Session Storage, you can choose the appropriate option to meet your specific use cases and enhance the user experience.

Thanks for reading!

For more content like this [click here](https://shefali.dev/blog/).

Keep coding!
<a href="https://www.buymeacoffee.com/devshefali" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/default-orange.png" alt="Buy Me A Coffee" height="41" width="174"></a>