What is a Cookie in JavaScript?

What is a Cookie in JavaScript?

Cookies are small text files that are stored on a user’s computer by a web browser. They are created when a user visits a website and are used to store information about the user’s activity on the site. Cookies can be used to remember user preferences, login information, and other data that can be helpful for a better user experience.

In JavaScript, cookies can be created, read, and deleted using the document.cookie property. This property returns a string that contains all the cookies that are currently set for the website. The string can be parsed into individual cookies using string manipulation methods.

To create a new cookie in JavaScript, you can set the document.cookie property to a string that contains the cookie’s name and value, as well as any additional options such as expiration date or path.

document.cookie = "username=johndoe; expires=Fri, 31 Dec 2021 23:59:59 GMT; path=/";

In this example, we are creating a cookie called username with the value johndoe. We are also setting an expiration date of December 31st, 2021 and a path of /, which means that the cookie will be available to all pages on the website.

To read a cookie in JavaScript, you can use the document.cookie property to get a string containing all the cookies for the website, and then parse the string to find the cookie you are looking for.

var cookies = document.cookie.split("; ");
for (var i = 0; i < cookies.length; i++) {
  var cookie = cookies[i].split("=");
  if (cookie[0] === "username") {
    console.log(cookie[1]);
  }
}

In this example, we are splitting the document.cookie string into an array of individual cookies, and then iterating over the array to find the username cookie. Once we find the cookie, we can log its value to the console.

To delete a cookie in JavaScript, you can set the cookie’s expiration date to a time in the past.

document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/";

In this example, we are setting the username cookie’s expiration date to January 1st, 1970, which will cause the cookie to be deleted.

Conclusion

Cookies are an important part of web development, as they allow websites to remember user preferences and login information. In JavaScript, cookies can be created, read, and deleted using the document.cookie property, and can be manipulated using string manipulation methods. By understanding how cookies work, you can create more personalized and user-friendly websites.