JavaScript - Cookies

JavaScript Cookies are small text files stored by a browser on a user's device that can be used to remember user preferences and data between visits to a website. Cookies can store information such as user login status, shopping cart contents, or any other data that needs to persist across multiple requests.

Cookies are set by a server and retrieved by a browser using JavaScript. The document.cookie property can be used to get and set the value of cookies.

// Setting a cookie

document.cookie = "username=John Doe; expires=Thu, 18 Dec 2023 12:00:00 UTC; path=/";

 

// Reading a cookie

let cookies = document.cookie.split(";");

 

for (let i = 0; i < cookies.length; i++) {

  let cookie = cookies[i].trim();

  if (cookie.startsWith("username=")) {

    console.log(cookie.substring("username=".length)); // Output: "John Doe"

  }

Cookies are widely used to store user information, but they have limitations, such as a limited size and the need to be sent with every request, which can slow down the performance of a website. Alternative solutions such as local storage and session storage are available for storing larger amounts of data on a user's device, but have different scope and lifespan.