---
title: "Cookie in JavaScript"  
description: "Cookie in JavaScript"  
author: "Anonymous User"  
published: 2021-07-19  
updated: 2023-11-29  
canonical: https://www.mindstick.com/forum/156523/cookie-in-javascript  
category: "javascript"  
tags: ["javascript"]  
reading_time: 2 minutes  

---

# Cookie in JavaScript

How to Set [cookie](https://www.mindstick.com/blog/123/what-is-cookie-poisoning) and get cookie with [JavaScript](https://www.mindstick.com/articles/874/how-to-create-watermark-text-for-textbox-by-using-javascript)?

## Replies

### Reply by Aryan Kumar

In JavaScript, cookies are small pieces of data stored on the client-side (in the user's browser). They are commonly used to store information about the user or their preferences. Here's how you can work with cookies in JavaScript:

### Setting a Cookie:

You can set a cookie using the **document.cookie** property. Here's an example:

```plaintext
// Function to set a cookie
function setCookie(name, value, daysToExpire) {
    var expires = "";

    if (daysToExpire) {
        var date = new Date();
        date.setTime(date.getTime() + (daysToExpire * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toUTCString();
    }

    document.cookie = name + "=" + value + expires + "; path=/";
}

// Example: Set a cookie named "username" with value "John" that expires in 7 days
setCookie("username", "John", 7);
```

### Reading a Cookie:

To read a cookie, you can use the **document.cookie** property or create a function to get a specific cookie value by name (as shown in the previous response):

```plaintext
// Function to get a specific cookie value by name
function getCookie(name) {
    var cookies = document.cookie.split(';');

    for (var i = 0; i < cookies.length; i++) {
        var cookie = cookies[i].trim();

        if (cookie.startsWith(name + '=')) {
            return cookie.substring(name.length + 1);
        }
    }

    return null;
}

// Example: Read the value of the "username" cookie
var usernameValue = getCookie('username');
console.log('Username:', usernameValue);
```

### Deleting a Cookie:

To delete a cookie, you can set its expiration date to a date in the past:

```plaintext
// Function to delete a cookie by name
function deleteCookie(name) {
    setCookie(name, "", -1);
}

// Example: Delete the "username" cookie
deleteCookie('username');
```

Remember that cookies are limited in size and are sent with every HTTP request, so it's important to use them judiciously and consider other storage options (like Local Storage or Session Storage) for larger amounts of data.


---

Original Source: https://www.mindstick.com/forum/156523/cookie-in-javascript

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
