What are Cookies in JavaScript?
What are Cookies in JavaScript?
What are Cookies in JavaScript?
Answer: Cookies are small pieces of text data (name=value pairs) that a website stores in the user's browser, and JavaScript can read and write them through document.cookie.
HTTP is stateless: the server forgets the user after each request. Cookies let a site remember things such as login status, preferences or items in a cart. The browser sends the cookies back to the same site with every request.
// create a cookie that expires on a given date
document.cookie = "username=Riya; expires=Fri, 31 Dec 2027 12:00:00 UTC; path=/";
// read all cookies (one string: "a=1; b=2")
console.log(document.cookie);
// delete: set an expiry date in the past
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/";
Points to remember: each cookie is limited to about 4 KB; a cookie without expires/max-age is a session cookie and is deleted when the browser closes; cookies marked HttpOnly cannot be read by JavaScript.
Log in or create a free account to answer this question.