How to work with cookies and local storage in JavaScript?

Working with cookies and local storage in JavaScript involves using the document.cookie property for cookies and the localStorage object for local storage.

Here's how you can work with cookies:

  1. Set a cookie: You can set a cookie by assigning a string value to document.cookie. The string should have the format name=value; expires=expiry_date; path=path_to_relevant_pages. For example:
document.cookie = "username=John; expires=Fri, 31 Dec 2021 23:59:59 GMT; path=/";
  1. Read a cookie: You can read a cookie by accessing document.cookie, which returns all the cookies in the form of a string. You can then parse this string to find the value of a specific cookie. Here's an example of reading the "username" cookie:
const cookies = document.cookie; const cookieArray = cookies.split('; '); for (let i = 0; i < cookieArray.length; i++) { const cookie = cookieArray[i]; const keyValue = cookie.split('='); const name = keyValue[0]; const value = keyValue[1]; if (name === "username") { console.log(value); break; } }
  1. Delete a cookie: To delete a cookie, you can set its expiry date to a past date. For example:
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/";

Here's how you can work with local storage:

  1. Set an item in local storage: You can set an item in local storage by using the localStorage.setItem(key, value) method. For example:
localStorage.setItem("username", "John");
  1. Get an item from local storage: You can retrieve an item from local storage by using the localStorage.getItem(key) method. For example:
const username = localStorage.getItem("username"); console.log(username);
  1. Remove an item from local storage: You can remove an item from local storage by using the localStorage.removeItem(key) method. For example:
localStorage.removeItem("username");

Note that both cookies and local storage have limitations such as size restrictions and cross-site scripting (XSS) concerns.