JAVASCRIPT Tutorial
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 Storage:
document.cookie
stores a string representing all cookies for the current domain.document.cookie = "username=John Doe";
Cookie Retrieval:
split()
method to extract individual cookies from the string.var username = document.cookie.split(";")[0].split("=")[1];
Cookies can be used for both session management (expire when the browser closes) and persistent data (expires after a specified time).
document.cookie = "sessionID=123; Max-Age=0"
document.cookie = "userID=456; Max-Age=3600"
(expire in 1 hour)// 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"