> For the complete documentation index, see [llms.txt](https://olise-eke.gitbook.io/frontend-tutorial-for-beginners/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://olise-eke.gitbook.io/frontend-tutorial-for-beginners/overview/javascript/javascript-cookies.md).

# Javascript Cookies

Cookies are little text files that a website stores on a user's device in JavaScript. They are frequently used to keep data like user preferences, login information, and the items of purchasing carts. Here's an illustration of how to make a cookie in JavaScript:

<mark style="color:red;">`document.cookie`</mark>` ``=`` `<mark style="color:blue;">`"username=Olise";`</mark>

In this example, you will  set a cookie named username with the value of Olise. The `document.cookie` property is used to access the cookie functionality in JavaScript.&#x20;

{% hint style="info" %}
Note that when creating a cookie, you should always include an expiration date so that the cookie is automatically deleted after a certain period of time.
{% endhint %}

&#x20;This is an example that includes an expiration date:

```
let date = new Date(); date.setTime(date.getTime() + (7 * 24 * 60 * 60 * 1000)); // expire in 7 days let expires = "expires=" + date.toUTCString(); 
document.cookie = "username=Olise;" + expires;
```

In this example, you will set a cookie named username with the value of Olise and an expiration date of 7 days from the current time.&#x20;

{% hint style="info" %}
Note that the expires variable is set to a string that specifies the expiration date in UTC format.
{% endhint %}

To read a cookie in JavaScript, you can use the `document.cookie` property to access the entire cookie string, and then parse it to extract the value of a specific cookie.

&#x20;Example:

```
let cookies = document.cookie.split(";"); 
for (let i = 0; I < cookies.length; i++) { let cookie = cookies[i].trim(); 
if (cookie.startsWith("username=")) { let value = cookie.substring("username=".length); 
console.log("Username: " + value); } }
```

In this example, you will use the split() method to split the `document.cookie` string into an array of individual cookies. We then loop through the array, and for each cookie, we trim any whitespace and check if it starts with the name of the cookie we're interested in (in this case, username). If you find a match, you extract the value of the cookie using the substring() method and print it to the console using console.log().
