Understanding Web Storage: localStorage and sessionStorage

Understanding Web Storage: localStorage and sessionStorage

localStorage and sessionStorage are both parts of the web storage API and are great tools to save key/value pairs locally i.e. they store data in the browser. The difference between them is that data in localStorage doesn't expire while data in sessionStorage is cleared when the page session ends( when window or tab is closed). Data stored in either localStorage or sessionStorage is specific to the protocol of the page.

Significant Differences:

LocalStorage

  • It stores data with no expiration date and gets cleared only through JavaScript, or by clearing the Browser cache/locally stored data.
  • Its storage limit is larger than that of a cookie and sessionStorage
  • Data is shared between all tabs and windows from the same origin.

SessionStorage

  • The sessionStorage object stores data only for a session, meaning that the data is stored until the browser (or tab) is closed.
  • However, it is shared between iframes in the same tab (assuming they come from the same origin).
  • The data survives page refresh, but not closing/opening the tab.

How to use localStorage and sessionStorage.

localStorage and sessionStorage accomplish the exact same thing and have the same API. Also, they have the same syntax(methods and properties) but the functionality for sessionStorage is much more limited.

Let's take a look at their methods:

Creating Entries

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

let key = 'Item 1';
localStorage.setItem(key, 'Value');

Reading Entries

Read entries with getItem:

let myItem = localStorage.getItem(key);

Updating Entries

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

localStorage.setItem(key, 'Value');

Deleting Entries

Delete an entry with the removeItem method:

localStorage.removeItem(key);

Clearing Everything

To remove everything in the localStorage:

localStorage.clear();

Checking for Items

Here’s how you can test for the presence of items in the localStorage:

if (localStorage.length > 0) {
  // We have items
} else {
  // No items
}

Checking for Support

Test for localStorage support by checking if it’s available on the window object:

if (window.localStorage) {
  // localStorage supported
}

Iterating Over Items

localStorage or sessionStorage don’t have a forEach(), but you can iterate over the items with a traditional for loop:

for (let i = 0; i < localStorage.length; i++){
  let key = localStorage.key(i);
  let value = localStorage.getItem(key);
  console.log(key, value);
}

or even the for in loop:

// Not gonna work as intended
for(let key in localStorage) {
  //shows getItem, setItem and other built-in stuff
}

So we wither need to filter fields from the prototype with hasOwnProperty check:

for(let key in localStorage) {
  if (!localStorage.hasOwnProperty(key)) {
     // skip keys like 'setItem' etc
  }
  // code ...
}

Or just get the “own” keys with Object.keys and then loop over them if needed:

let keys = Object.keys(localStorage);
for(let key of keys) {
  // code ...
}

Storing JSON Objects

Only strings can be stored in localStorage or sessionStorage, but you can use JSON.stringify() to store more complex objects and JSON.parse() to read them:

// Create item:
let myObj = { name: 'color', hexValue: '#000' };
localStorage.setItem(key, JSON.stringify(myObj));

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

I believe this helps someone. Keep pushing and don't relent

Happy Coding ...