localStorage
allows web applications to store and access data on the client-side right in the browser using JavaScript. Data stored in the local storage by the web application can be accessed by current origin only.
Window.localStorage
or simply localStorage
stores data forever until it is cleared by the application. This is different than sessionStorage
where the storage is cleared when browser is closed. Also, the data remain in sync if the user has multiple tabs open of the same application.
Let’s explore various methods that are available under localStorage
API.
localStorage.setItem()
method allows storing data in key & value pairs where both key and value should be in String format. To store JSON object in local storage first we need to convert that in a string using JSON.stringify()
method.
// storing simple string localStorage.setItem('user', 'Gulshan Saini') // storing JSON object localStorage.setItem( 'userdetails', JSON.stringify({ city: 'New Delhi', country: 'India' }) )
To access data from localStorage
we can use method localStorage.getItem()
. The getItem()
method accepts key in string format as argument. If the key is not found null
is returned
// get key user from local storage localStorage.getItem('user') // Gulshan Saini
To remove localStorage
item we can use method localStorage.removeItem()
. The removeItem()
method accepts key in string format as an argument.
// remove key user from local storage localStorage.removeItem('user')
To clear local storage we can use clear()
method. This will clear all the local storage items.
// clear all local storage items localStorage.clear()