HomeTutorsContact

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.

Example

// storing simple string
localStorage.setItem('user', 'Gulshan Saini')

// storing JSON object
localStorage.setItem(
  'userdetails',
  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

Example

// 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.

Example

// remove key user from local storage
localStorage.removeItem('user')

Clearing local storage

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

Example

// clear all local storage items
localStorage.clear()

Tags

#html
Previous Article
How to launch the Firefox browser using puppeteer?
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.

Topics

CSS
Gatsby
Browser
HTML
JavaScript
NextJS
Puppeteer
NodeJS
Python
ReactJS
Typescript
VSCode

Related Posts

What is rel noopener?
October 30, 2020
1 min
© 2021, All Rights Reserved.

Quick Links

Contact UsBrowserCSSPythonPuppeteer

Social Media