Introduction to JavaScript cookies

What are cookies?

Cookies are small text files that are stored on a user’s device when they visit a website. These files contain data such as user preferences or session information. Each cookie is associated with a specific website and can be accessed and modified by that website.

How are cookies used?

Cookies have various uses in web development, including:

Creating and accessing cookies

In JavaScript, cookies can be created and accessed using the document.cookie property. To create a cookie, you can assign a value to document.cookie as follows:

document.cookie = "name=value";

To access the value of a cookie, you can read the document.cookie property:

let cookies = document.cookie;

Setting expiration and domain

By default, cookies have no expiration date and are deleted when the browser is closed. However, you can set an expiration date for a cookie using the expires attribute. For example:

document.cookie = "name=value; expires=Fri, 31 Dec 2021 23:59:59 GMT";

You can also specify the domain for which the cookie is valid using the domain attribute:

document.cookie = "name=value; domain=example.com";

Deleting cookies

To delete a cookie, you can set its expiration date to a time in the past. This will cause the browser to immediately delete the cookie. For example:

document.cookie = "name=; expires=Thu, 01 Jan 1970 00:00:00 GMT";

Conclusion

JavaScript cookies are a powerful tool in web development for maintaining user preferences, session information, and personalized experiences. By understanding how to create, access, and delete cookies, developers can enhance the functionality and user experience of their websites. #webdevelopment #JavaScriptcookies