JavaScript Deleting Cookies
Syntax
document.cookie = "cookieName=; expires=Thu, 01 Jan 1970 00:00:00 UTC";
Example
Here's an example deleting a cookie named username
:
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC";
Output
Deleting a cookie using JavaScript will remove the cookie from the browser.
Explanation
Cookies are small text files that are stored on a user's computer by a website. They are used to remember user preferences, login information, and other data. Sometimes it may be necessary to remove a cookie from a user's computer, either to clear out unused data or to protect user privacy.
To delete a cookie using JavaScript, we set the cookie's value to an empty string and specify a past expiration date (in this case, January 1, 1970). This tells the browser that the cookie has expired and should be removed from the user's computer.
Use
Deleting cookies is often done in response to a user action, such as logging out of a website. It may also be used to clear out old or unused cookies that could potentially cause issues with website functionality.
Important Points
- When deleting a cookie, make sure to set the expiration date to a date in the past.
- Deleting a cookie using JavaScript only removes the cookie from the user's browser. The cookie may still exist on the server or in other user devices.
Summary
In JavaScript, deleting cookies is done by setting the cookie's value to an empty string and specifying a past expiration date. This removes the cookie from the user's browser and is often used to clear out old or unused cookies or to protect user privacy.