localStorage is a way of saving the key-value pair in the web browser and the best part about it is that there is no expiration date meaning that data will still be there in the browser even if you reload the page.
How does localStorage work?
to storage the localStorage in your web application, you can use the listed methods:
- setItem() : adds key value to localStorage
- getItem() : retrieve the items you entered in localStorage
- clear(): to clear the local storage
Where is localStorage stored?
it depends upon the browsers that how and where they are storing it, for example, Firefox stores localstorage in webappsstore.sqlite
file in the profile folder.
What is window.localStorage?
localStorage is available via the windows.localStorage property which is a part of the Window interface in Javascript that represents the window containing the DOM Document.
setItem()
it is a method to store the values in localStorage object
it takes two parameters: key and a value
window.localStorage.setItem('name', 'Ansub Khan')
over here you can see that ‘name’ is basically a key that stores the value ‘Ansub Khan’, now the thing is that localStorage only stores String but what if we have to store data of different data types like an array?
for that we use a method called JSON.stringify() before passing it to setItem().
const person = {
name: "Ansub Khan",
age: 21
}
window.localStorage.setItem('user', JSON.stringify(person));
getItem()
it is used to access the data that you have stored in the localStorage using setItem() method.
window.localStorage.getItem('user')
// this is going to give us
'{"name":"Ansub Khan","age":21}'
now to use this value as an object you need to convert it back to an object, if you remember localStorage stores data in String format, that’s why we used JSON.stringify(), now to convert it back to object we are going to use JSON.parse()
JSON.parse(window.localStorage.getItem('user'));
clear()
it is used to delete the data that we saved in local storage, you can see the localStorage in Chrome, open inspect element, and then click on the application, there you are going to find the local storage as seen in the image below
on using this method
window.localStorage.clear()
it will get empty like it was before.
Local Storage has some limitations tho:
- Do not store sensitive user information in localStorage
- It is not a substitute for a server-based database as information is only stored on the browser
- localStorage is limited to 5MB across all major browsers
- localStorage is quite insecure as it has no form of data protection and can be accessed by any code on your web page