What are JavaScript cookies?

  • Share this:

In the context of web programming, a cookie is a small piece of data that is stored in a user's web browser by a website. Cookies are used to store information about the user, such as preferences and browsing history so that the website can personalize the user's experience and remember their preferences when they return to the website.

In JavaScript, cookies can be created, read, and deleted using the `cookie` property of the `document` object.

Here is an example of how to create a cookie in JavaScript:

document.cookie = "username=John Smith; expires=Fri, 31 Dec 2021 12:00:00 UTC; path=/";

This code creates a cookie called "username" with a value of "John Smith" and an expiration date of December 31, 2021. The `expires` attribute specifies when the cookie should be deleted. The `path` attribute specifies the `path` on the server to which the cookie should be sent.

To read a cookie in JavaScript, you can use the `getCookie` function shown below:

function getCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for (var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') c = c.substring(1, c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
  return null;

To use this function, pass in the name of the cookie as a parameter. For example:

var username = getCookie("username");

To delete a cookie in JavaScript, you can set its expiration date to a date in the past:

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

Keep in mind that cookies are stored on the user's computer and can be deleted by the user at any time. They are also subject to browser and device limitations on the amount of data that can be stored.


About author
I am a professional web developer. I love programming and coding, and reading books. I am the founder and CEO of StorialTech.