• Tutorials Logic, IN
  • +91 8092939553
  • info@tutorialslogic.com

Cookies in JavaScript

Cookies

A JavaScript cookie is a piece of data stored in small text files, on our computer to be accessed by our web browser. In many situations, using cookies is the most useful and efficient way of remembering user data like tracking preferences, purchases, commissions, and other information which is required for better user experience. Cookies has 5 variable-length fields, which include following-

Name:- It is used to set and retrieved the cookies using key name and its value.

Expires or max-age:- It is used to set the expiry date and time for cookies. If a cookie doesn’t contain one of these options, it disappears when the browser is closed.

Domain:- It is used to set the domain name for the cookies.

Path:- It is used to set the path for the cookies. Once the path sets the cookie will be accessible for pages under that path. If a cookie doesn’t contain path option, then it will take the current path.

Secure:- If the cookie contains the word "secure", then cookie may only be retrieved or fetched with a secure server. If a cookie doesn’t contain "secure" option, then no such restriction exists.

Creating a Cookie

A cookie can be easily created using document.cookie in JavaScript like below-

										    
											document.cookie = "Cookie_name = Cookie_value; expires = Wed, 21 Aug 2019 21:00:00 UTC; path = /"
											
										

Updating a Cookie

A cookie can be easily updated using document.cookie in JavaScript like below-

										    
											document.cookie = "Cookie_name = Cookie_value; expires = Wed, 27 Nov 2019 23:00:00 UTC; path = /"
											
										

The old cookie will be overwritten bye new cookie.

Retrieving a Cookie

A cookie can be easily retrieved using document.cookie in JavaScript like below-

										    
											const cookies = document.cookie;
											
										

In JavaScript document.cookie will return all the available cookies in one string, like- cookie1 = value; cookie2 = value; cookie3 = value;

Deleting a Cookie

To delete a cookie, just set the value of the cookie to empty and expires parameter to a passed date.

										    
											document.cookie = "Cookie_name = ; expires = Thu, 01 Jan 1970 00:00:00 UTC; path = /"