80. What is a cookie in JavaScript?
easy

In JavaScript, a cookie is a small text file that is stored on a user's computer or mobile device by a website or application. Cookies contain information about a user's preferences, browsing history, and other data that can be used to personalize their experience on the website.


Cookies are needed because they allow websites to remember information about a user and provide them with a more personalized experience. For example, if a user has previously logged into a website, a cookie can store their login credentials so they don't have to enter them every time they visit. Additionally, cookies can be used to track a user's browsing history and provide them with targeted advertising or other personalized content.


There are several options that can be set for cookies in JavaScript, including:

  1. Session cookies: These cookies are temporary and are deleted when the browser closes. They are used to store information that is needed for the current session, such as a user's shopping cart on an e-commerce website.
  2. Persistent cookies: These cookies are stored on the user's computer and remain after the browser closes. They are used to remember information about a user's preferences and other data that can be used to personalize their experience on the website.
  3. Secure cookies: These cookies are encrypted and can only be accessed by the website or application that set them. They are often used for authentication and other security-related purposes.

To delete a cookie in JavaScript, you can typically use the delete keyword to remove the cookie from the document's cookie property. Here's an example:

// Delete the 'myCookie' cookie
document.cookie = "myCookie=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/;
 domain=example.com";

In this example, we are deleting the myCookie cookie by setting its expires property to a date in the past (in this case, January 1st, 1970), and setting its path and domain properties to / and example.com, respectively. This tells the browser that all subdomains of the example.com domain should delete the cookie.