How do I clear local storage using javascript?

Hello, I am able to add localStorage using Item keys using Javascript, with below sample code

localStorage.setItem("test", "TestValue");

But I would like to know, how can I clear localStorage using Javascript, and how to remove all localStorage keys using single code.

Asked by:- bhanu
: 1077 At:- 5/12/2021 2:07:14 PM
Javascript clear local storage javascript

2 Answers
profileImage Answered by:- vikas_jk

You can clear or delete key in localStorage using Javascript as per below example

localStorage.removeItem("KeyName"); //remove item from local storage based on key name

To Clear all keys at once

localStorage.clear();  //clear all key at once

To Retrieve value based on keys

// Retrieve the object from storage
var retrievedValue = localStorage.getItem('YourKeyName');

Read Local storage in javascript for more complete details about localStorage in Javascript.

At:- 5/12/2021 2:45:02 PM
Thanks for you answer, I will check the detailed article also. 0
By : bhanu - at :- 5/12/2021 3:09:28 PM

profileImage Answered by:- Vinnu

You should use "window" to remove global storage



If you want to delete or clear local storage on windows load

window.onbeforeunload = function() {
  return '';

This should work.

At:- 6/22/2022 8:50:08 AM

Login/Register to answer
Register directly by posting answer/details

Full Name *

Email *

By posting your answer you agree on privacy policy & terms of use

Subscribe Now

Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly