JavaScript Cookies
Cookies are small pieces of data that are stored on the client's machine by the web server. Cookies are used to remember user preferences, login information, and preferences for a given site. In JavaScript, cookies can be created using the document.cookie
method.
Syntax
document.cookie = "cookieName=cookieValue; expires=expirationDate; path=pathName";
cookieName
: The name of the cookie.cookieValue
: The value of the cookie.expirationDate
: The date and time when the cookie will expire. If not specified, the cookie will expire at the end of the session.pathName
: The path of the cookie. If not specified, the cookie will be set for the current page.
Example
// Setting a cookie
document.cookie = "username=John Doe; expires=Thu, 18 Dec 2022 12:00:00 UTC; path=/";
// Reading a cookie
const username = getCookie("username");
alert(`Welcome ${username}`);
function getCookie(cookieName) {
const name = cookieName + "=";
const decodedCookie = decodeURIComponent(document.cookie);
const cookieArray = decodedCookie.split(';');
for(let i = 0; i < cookieArray.length; i++) {
let c = cookieArray[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
Output
When the above code is executed, the username
cookie will be set with the value of John Doe
and an expiration date of Thu, 18 Dec 2022 12:00:00 UTC
. When the user visits the page again, the cookie will be read and the user will be welcomed with an alert message.
Explanation
- The
document.cookie
method is used to set or read a cookie. - When setting a cookie, the
expires
andpath
parameters are optional. - The
expires
parameter is used to set the expiration date of the cookie. - The
path
parameter is used to set the path of the cookie. - When reading a cookie, the
getCookie
function is used to retrieve the value of the cookie.
Use
- Cookies can be used to remember user preferences, login information, and preferences for a given site.
- Cookies can be used to personalize content for the user.
- Cookies can be used to track user behavior on the site.
Important Points
- Cookies are limited to 4KB in size.
- Cookies can only be accessed by the domain that sets them.
- Cookies can be deleted with JavaScript using the
document.cookie
method and setting the expiration date to a past date.
Summary
JavaScript cookies are used to store small pieces of data on the client's machine. They can be created using the document.cookie
method and can be used to remember user preferences, login information, and preferences for a given site. Cookies are limited to 4KB in size and can only be accessed by the domain that sets them. They can be deleted with JavaScript by setting the expiration date to a past date.