How to use localStorage in web application using JavaScript?

By Gulshan Saini
Published in JavaScript
July 07, 2020
1 min read

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.

Storing data in localStorage

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
  JSON.stringify({ city: 'New Delhi', country: 'India' })

Accessing localStorage items

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

Removing localStorage item

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

Clearing local storage

To clear local storage we can use clear() method. This will clear all the local storage items.


// clear all local storage items


Previous Article
How to launch the Firefox browser using puppeteer?

Related Posts

CSS RGB color codes including hex values
December 07, 2021
1 min
Gulshan Saini

Gulshan Saini

Fullstack Developer



Subscribe to our newsletter!

We'll send you the best of our blog just once a month. We promise.

Quick Links

Contact UsBrowserCSSPythonPuppeteer

Social Media