In JavaScript, you can delete cookies by setting their expiration date to a time in the past or by explicitly removing them using the document.cookie
property. Deleting cookies is useful for scenarios where you want to remove stored data, such as when a user logs out of a website or when certain preferences need to be reset.
Setting Cookie Expiration to the Past:
- To delete a cookie, you can set its expiration date to a time in the past. When the browser sees that a cookie has expired, it automatically removes it from the cookie storage.
document.cookie = "username=;
expires=Thu, 01 Jan 1970 00:00:00 UTC;
path=/;";
Explanation:
- In the example above, a cookie named
username
is being deleted by setting its expiration date toThu, 01 Jan 1970 00:00:00 UTC
, which is a time in the past. This effectively tells the browser to remove theusername
cookie.
Using Max-Age Attribute:
- Alternatively, you can use the
max-age
attribute to specify the maximum age of the cookie in seconds. Setting it to a negative value effectively deletes the cookie.
document.cookie = "username=;
max-age=0; path=/;";
Explicitly Removing Cookies:
- You can also explicitly remove cookies by setting their value to an empty string and optionally specifying attributes like
expires
ormax-age
.
document.cookie = "username=;
expires=Thu, 01 Jan 1970 00:00:00 UTC;
path=/;";