Storing and Clearing Objects in localStorage javascript

Hello Everyone Today in this blog we are going to know about the Storing and Clearing Objects in localStorage javascript. So, first of all, Web storage objects localStorage allow saving key/value pairs in the browser.

The main features of localStorage are:

  • Shared between all tabs and windows from the same origin.
  • The localStorage object stores data with no expiration date.
  • The data will not be deleted when the browser is closed and will be available the next day, week, or year even OS reboot.
  • The localStorage property is read-only.

You May Also Like:

Storage objects provide the same methods and properties:

  • setItem(key, value) – store key/value pair.
  • getItem(key) – get the value by key.
  • removeItem(key) – remove the key with its value.
  • clear() – delete everything.
  • key(index) – get the key on a given position.
  • length – the number of stored items.

localStorage Example

var testObject = { 'one': 1, 'two': 2, 'three': 3 };

// Put the object into storage
localStorage.setItem('testObject', JSON.stringify(testObject));

// Retrieve the object from storage
var retrievedObject = localStorage.getItem('testObject');

console.log('retrievedObject: ', JSON.parse(retrievedObject));

Looping Over Keys

As we’ve seen, the methods provide “get/set/remove by key” functionality. But how to get all saved values or keys? Unfortunately, storage objects are not iterable. One way is to loop over them as over an array:

for(let i=0; i<localStorage.length; i++) {
  let key = localStorage.key(i);
  alert(`${key}: ${localStorage.getItem(key)}`);
}

Summary

Storing and Clearing Objects in localStorage in javascript is very easy to use.

Objects in localStorage allow storing key/value in the browser.

  • Both key and value must be strings.
  • The limit is 2mb+, depends on the browser.
  • They do not expire.

Storage event:

  • Triggers on setItemremoveItemclear calls.
  • Contains all the data about the operation (key/oldValue/newValue), the document url and the storage object storageArea.
  • Triggers on all window objects that have access to the storage except for the one that generated it  globally for localStorage.

Thank you for reading this blog, share this blog as much as possible and also show it to your friends. If you have any questions, feel free to comment.

Leave a Reply

Your email address will not be published. Required fields are marked *

%d