What is Local Storage and Session Storage

How to Solve:

LocalStorage & SessionStorage are web storage API, That is used for save, Read, delete data based to Key/Value Pairs Locally.

Diffrance between LocalStorage & SessionStorage

  • LocalStorage Provides 5MB/10MB Storage While SessionStorage Provides 5MB
  • LocalStorage it’s not session based and its working in same origin policy while SessionStorage is session based and working per window or tab
  • Both are used for Client side use only

Create Records in LocalStorage:

Create key/value pair entries with localStorage.setItem, providing a key and a value:

let tokenValue = 'abgfsjfvscbssjfsfbsdfdshhsfhfbsjdvfs';
localStorage.setItem('token', 'tokenValue');

Read values in LocalStorage:

We can read LocalStorage values using key

let myItem = localStorage.getItem('token');

Update data in LocalStorage:

Update an entry just as you would create a new one with setItem, but with a key that already exists:

let tokenValue = 'abgfsjfvscbssjfsfbsdfdshhsfhfbsjdvfs';
localStorage.setItem('token', 'tokenValue');

Delete data in LocalStorage:

Delete an entry with the removeItem method:

localStorage.removeItem('token');

Clear LocalStorage:

Here’s how to clear everything that’s stored in localStorage:

localStorage.clear();

How to Store Json Objects:

We can store Json Object using JSON.Stringify Method after that we can read data using JSON.Parse Method

// Create item:
let myObj = { firstName: 'James', lastName: 'Bond', age: 40 };
localStorage.setItem(key, JSON.stringify(myObj));

// Read item:
let item = JSON.parse(localStorage.getItem(key));