JAVASCRIPT Tutorial

JS Cookies

What are Cookies?

Cookies are small text files stored on the user's computer by a website. They help websites remember user settings and other information for future visits.

Cookie Management in JavaScript

Cookie Storage:

  • document.cookie stores a string representing all cookies for the current domain.
  • Example: document.cookie = "username=John Doe";

Cookie Retrieval:

  • Use the split() method to extract individual cookies from the string.
  • Example: var username = document.cookie.split(";")[0].split("=")[1];

Session Management and Persistent Data

Cookies can be used for both session management (expire when the browser closes) and persistent data (expires after a specified time).

  • Session Cookies: document.cookie = "sessionID=123; Max-Age=0"
  • Persistent Cookies: document.cookie = "userID=456; Max-Age=3600" (expire in 1 hour)

Practical Example: Storing and Retrieving User Data

// Store user data
function setCookie(cname, cvalue) {
  document.cookie = `${cname}=${cvalue}; Max-Age=3600`;
}

// Retrieve user data
function getCookie(cname) {
  var cookies = document.cookie.split(";");
  for (var i = 0; i < cookies.length; i++) {
    var cookie = cookies[i].split("=");
    if (cookie[0] === cname) {
      return cookie[1];
    }
  }
  return null;
}

// Usage
setCookie("firstName", "Jane");
var firstName = getCookie("firstName"); // Output: "Jane"