Clearing localStorage in JavaScript?


There exists two ways actually to clear the localStorage via JavaScript.

Way1 − Using the clear() method

localStorage.clear();

Way2 − Iterating over localStorage and deleting all key

for(key in localStorage){
delete localStorage[key];
}

Both ways will work.

Example

<html>
<body>
<p id = "storage"></p>
<script>
if (typeof(Storage) !== "undefined") {
   localStorage.setItem("product", "Tutorix");
   // cleared before displaying
   localStorage.clear();
   document.getElementById("storage").innerHTML = localStorage.getItem("product");
}
else {
   document.getElementById("storage").innerHTML = "Sorry, no Web Storage
   compatibility...";
}
</script>
</body>
</html>

Updated on: 18-Aug-2020

364 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements