Local Storage


Local storage is used to store and access data in the browser without it expiring. The data that has been stored in the browser will remain even after the browser window has been closed.

Resource List

I have gotten some knowledge from this article: More on Local Storage

Methods for localStorage

  1. setItem( )
//This is used to store values in the localStorage object.
//It takes two parameters, a key and a value. The key stores the value just like a variable and it can be referenced later to get the value assigned to it.
//It is used like this:
window.localStorage.setItem('bestFood', 'Garri');
//Here the key is bestFood and the value is Garri.

//Using the setItem() to store objects;
const location = {
    country: 'England',
    city: 'Portsmouth'
window.localStorage.setItem('person', JSON.stringify(location));
  1. getItem( )
//This is used to get data stored in the browser's localStorage object.
//It takes only one parameter which is the key and then it returns the value of the key  as a string.
//It is used like this:
window.localStorage.getItem(bestFood); //result will be a string which is Garri.
//To get the value of person stored above, it is done this way
window.localStorage.getItem('person'); //result will be a string like this:  "{"country":"England","city": "Portsmouth"}". This is a JSON string.

//To get the data in object form, it is done this way;
  1. removeItem( )
//To remove an item, the removeItem() method is used like this;
//It takes the key as a parameter.
window.localStorage.removeItem('country'); //the country key will be removed.
  1. clear( )
//To clear the localStorage the clear() method used like this;
  1. key( )
//It is used to loop through keys and pass a number or index to localStorage to retrieve the name of the key.
var keyName = window.localStorage.key(index);

Quick Notes

  • Local storage can only store strings.
  • To store arrays or objects in local storage, it needs to be converted to strings. The JSON.stringify() method is used to turn it to strings.
  • It should not be used to store sensitive information as it has no form of data protection.
  • It should not be used in place of a database.
  • It is limited to 5MB on major browsers.

No Comments Yet