Local Storage and Session Storage in JavaScript

Local Storage and Session Storage in JavaScript

Beginners guide to local storage you can use in JavaScript.

Β·

2 min read

There are many instances when you would want to keep your data permanent even after reloading the page and not have to use any kind of backend. Well, this can be done using the browser's local storage that can be accessed by JavaScript.

Local Storage

The Local Storage allows you to save key/value pairs in a web browser.

The localStorage object stores data with no expiration date. Meaning that the data will not be deleted when the browser is closed and will be available the next day, week, or year. (The localStorage property is read-only.)

The syntax for SAVING data to localStorage:
localStorage.setItem("key", "value");
The syntax for RETRIEVING data from localStorage:
let lastname = localStorage.getItem("key");
The syntax for REMOVING data from localStorage:
localStorage.removeItem("key");

###Example:

// Saving Data
localStorage.setItem("Name", "Harry");

// Retrieving Data
let name = localStorage.setItem("Name");

//Removing Data
localStorage.removeItem("Name");

Note: One limitation of localStorage is that you can only store strings. Arrays and Objects are not allowed. But there is a work-around this is shown below.

Storing Objects in Local Storage

As you may have already guessed, Firstly, we will convert those arrays into strings. And then we will save them in localStorage. There is more than one way to do this, here we will use JSON.stringify and JSON.parse.

//Store
const myArr = {name: "Harry" , profession:"Developer");
localStorage.setItem("myArray", JSON.stringify(myArr));

//Retrieve
let myArr = JSON.parse(localStorage.getItem("myArray"));

You can check if the key-value pair is stored on not with the help of Chrome Developer Tools

  1. Open Developer Tools
  2. Go to Application Tab
  3. At the side menu, select local Storage. There you will see all the key-value pairs that are saved. (All domain's local Storage key-value pairs will be different. )

image.png

Session Storage

Session Storage is similar to localStorage, only with a few changes. Local Storage is permanent to the browser, so whether you close the browser or Shut down your computer, it remains stored. But the sessionStorage object stores data for only one session (the data is deleted when the browser tab is closed).

The syntax for SAVING data to sessionStorage:
sessionStorage.setItem("key", "value");
The syntax for RETRIEVING data from sessionStorage:
let lastname = sessionStorage.getItem("key");
The syntax for REMOVING data from sessionStorage:
sessionStorage.removeItem("key");

That is it for this blog. I hope you have understood Local Storage and Session Storage. If you have any questions, feel free to reach me at kashishdhingra64@gmail.com See you around!

Β