LocalStorage and SessionStorage in JavaScript
Published: 2022-02-12 17:31:46

Web storage is a concept that is simple to learn yet very powerful. You might have seen many websites with dark and light modes. When we reload the website, the mode remains the same although they are not using any database to store the mode. This is possible using **web storage**. 
You can access the data in any part of the code, even you can use the same data in various web pages. Web storage is simply storing the data in the browser. That's how the theme(dark/light) of the website remains the same on multiple pages of the website. This data is stored in your browser in the form of a [DOMString](https://developer.mozilla.org/en-US/docs/Web/API/DOMString) in a key-value pair.
There are two types of web storage, you can differ them on their expiration 

- Session Storage 
- Local Storage

## Session Storage:
In session storage, the data is stored for one session. As the user opens a new tab, the browser creates a new session and when the user closes the browser tab, the data in the sessionStorage gets deleted.

- To store data to sessionStorage

```
sessionStorage.setItem('myKey', 'myValue');
// or 
sessionStorage.myKey = "myValue";
// or
sessionStorage['myKey'] = "myValue";
```

- To get data from sessionStorage

```
sessionStorage.getItem('myKey');
// or
sessionStorage['myKey'];
// or
sessionStorage.myKey;
// Output: 'myValue'
```

- To clear specific data from sessionStorage
```
sessionStorage.removeItem('myKey')
```

- To clear all data from  sessionStorage

```
sessionStorage.clear()
```


## Local Storage:
Local storage has no expiration date. It is available for multiple sessions. Your data remains in localStorage till you delete it manually. Local storage is commonly used to store the theme(dark/light/other) in the web pages, save notes in a notes app.
The syntax for localStorage is quite similar to that of sessionStorage.

- To store data to localStorage
```
localStorage.setItem('myKey', 'myValue');
// or 
localStorage.myKey = "myValue";
// or
localStorage['myKey'] = "myValue";
```

- To get data from localStorage
```
localStorage.getItem('myKey');
// or
localStorage['myKey'];
// or
localStorage.myKey;
// Output: 'myValue'
```

- To clear specific data from sessionStorage
```
localStorage.removeItem('myKey')
```

- To clear all data from  sessionStorage
```
localStorage.clear()
```

## Let's code a simple counter to learn about localStorage
We are going to store the count in the localStorage.
When we refresh the page or reopen the tab, the counter does not start from 0. It will take the last value stored in localStorage.

## HTML
```
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Simple Counter</title>
    <link rel="stylesheet" href="./index.css" />
  </head>
  <body>
    <main>
      <div class="counter">
        <span class="dec" onclick="updateCounter('INC')">&#171;</span>
        <span class="value">0</span>
        <span class="inc" onclick="updateCounter('DEC')">&#187;</span>
      </div>
    </main>
    <script src="./index.js"></script>
  </body>
</html>

```

## CSS 
```
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

main {
  font-family: "Courier New", Courier, monospace;
}

.counter {
  width: max-content;
  margin: 10vh auto;
  display: flex;
  flex-direction: column;
  align-items: center;
  font-size: 16px;
}
.counter > span {
  padding: 0.5em;
}

.inc,
.dec {
  cursor: pointer;
  font-size: 3em;
  font-weight: 700;
  transform: rotate(90deg);
  color: #0b0c64;
}

.inc:hover,
.dec:hover {
  opacity: 0.8;
}

.value {
  font-size: 3em;
  min-width: 200px;
  min-height: 200px;
  background: #368bec;
  color: #fff;
  border-radius: 1em;
  display: grid;
  place-items: center;
  box-shadow: 0 0 0.5em 0 #00000073;
}

```

## JavaScript

```
const [inc, value, dec] = document.querySelector(".counter").children;

// Check counter exist in localStorage
// if not then initialise it to zero
if (!localStorage.counter) localStorage.counter = 0;

value.innerHTML = localStorage.counter;

const updateCounter = (action) => {
  switch (action) {
    case "INC":
      // since localStorage stores in DOMString
      // We have to convert it in number
      localStorage.counter = Number(localStorage.counter) + 1;
      break;
    case "DEC":
      localStorage.counter = Number(localStorage.counter) - 1;
      break;
  }
  value.innerHTML = localStorage.counter;
};

```

{% codepen https://codepen.io/Vilay_17/pen/RwjZbar %}