Sometimes, we want to clear local storage, session storage and cookies in JavaScript.
In this article, we’ll look at how to clear local storage, session storage and cookies in JavaScript.
How to clear local storage, session storage and cookies in JavaScript?
To clear local storage, session storage and cookies in JavaScript, we use the clear
method to clear local and session storage and update the cookie string.
For instance, we write
localStorage.clear();
to clear local storage.
We write
sessionStorage.clear();
to clear session storage.
And to clear cookies, we write
const cookies = document.cookie;
for (const myCookie of cookies.split(";")) {
const pos = myCookie.indexOf("=");
const name = pos > -1 ? myCookie.substr(0, pos) : myCookie;
document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
}
to split the document.cookie
string into individual key-value pairs with split
.
We loop through each item in the array returned by split
with a for-of loop.
Then we get the index of '='
in each string with indexOf
.
And then we get the name
value by using substr
if pos
is bigger than -1 or use myCookie
itself otherwise.
Then we set document.cookie
to an expiry date that’s before the current date and time to make it expire.
Conclusion
To clear local storage, session storage and cookies in JavaScript, we use the clear
method to clear local and session storage and update the cookie string.