What is local Storage?
local storage is property for accessing Storage object, which is used to store and retrieve data from user’s browser. It is accessible only at client side not at server side like cookie.
Data stored in localStorage is accessible thought all pages under same domain, until user does not delete it manually. Even though user closes the browser, data will be accessible next time.
Syntax:
Set local storage: localStorage.setItem('ProductName', 'Mobile');
localStrorage stores data in Key/Value format. Same syntax can be written as
localStorage.ProductName = 'Mobile';
Note: Here ProductName is key and Mobile is value for local storage. Key is case sensitive so here ProductName and productname will be considered as two different keys.
Get local storage:
var ProductName = localStorage.getItem('ProductName');
OR
var ProductName = localStorage.ProductName;
localStorage will always return value in string. So if required, then one need to cast the value in needed type.
Remove local storage:
localStorage.removeItem('ProductName');
This will remove ‘ProductName’ from local storage of under current domain.
localStorage.clear();
This will remove all the local storage for current domain.
What is session Storage?
Session storage is almost same as local storage. Only difference is, session storage will get cleared once user will close the browser window.
Syntax:
All the example written for localStorage can be used for sessionStorage as below
Set session storage:
sessionStorage.setItem('ProductName', 'Mobile');
OR
sessionStorage.ProductName = 'Mobile';
Get session storage:
var ProductName = sessionStorage.getItem('ProductName');
OR
var ProductName = sessionStorage.ProductName;
Remove session storage:
sessionStorage.removeItem('ProductName'); sessionStorage.clear();
Browser Support for Local Storage and Session Storage:
Browser | Version |
Chrome | 4.0 |
Firefox | 3.5 |
Internet Explorer | 8.0 |
Opera | 10.50 |
Safari | 4.0 |
Storage Capacity:
Storage capacity for localStorage and sessionStorage is vary based on browser. Generally browsers provides around 5MB of storage space.
Click Here to read more JavaScript articles on Code4Developers. If you are getting started with Angular then I recommend this official documentation to refer.
I have healthy knowledge and experience in Azure, O365 and ASP.Net with c#, MVC, WebApi along with client-side frameworks and libraries like JavaScript, JQuery, KnockoutJs, AngularJs, Angular, ReactJs, NodeJs
3 comments
Nice, worked for me thanks
Code is fine but please provide more info for beginners
Can you please share knowledge about how to use an object for localstorage in angular 7