Clearing localStorage in JavaScript?

JavascriptWeb DevelopmentObject Oriented Programming

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>
raja
Updated on 18-Aug-2020 07:16:30

Advertisements