JavaScript Cookies

Cookies are small pieces of data stored on the user's browser. They are used to remember information such as user preferences, session details, and other client-side data.

Key Topics

Creating Cookies

Cookies can be created by assigning a string to the document.cookie property. The cookie string includes the name, value, and optional attributes such as expires and path.

document.cookie = "username=JohnDoe; expires=Fri, 31 Dec 2024 23:59:59 GMT; path=/";
console.log("Cookie set:", document.cookie);

Explanation: The document.cookie property is used to set a cookie with the name username and value JohnDoe. The expires attribute specifies the expiration date, and path determines the scope of the cookie.

Reading Cookies

All cookies for the current domain are stored in the document.cookie string, separated by semicolons. You can parse this string to retrieve specific cookies.

console.log("All cookies:", document.cookie);

// Function to get a specific cookie by name
function getCookie(name) {
    let cookies = document.cookie.split('; ');
    for (let cookie of cookies) {
        let [key, value] = cookie.split('=');
        if (key === name) return value;
    }
    return null;
}

console.log("Username cookie:", getCookie("username"));

Explanation: The getCookie function parses the document.cookie string to find a specific cookie by its name and returns its value.

Deleting Cookies

To delete a cookie, set its expiration date to a past date using the expires attribute.

// Delete the username cookie
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/";
console.log("Deleted cookie:", document.cookie);

Explanation: Setting the expires attribute of a cookie to a date in the past effectively deletes it from the browser.

JavaScript Usage in DOM

Below is a DOM-based example demonstrating how to create, read, and delete cookies dynamically.

<!DOCTYPE html>
<html>
    <head>
        <title>JavaScript Cookies Example</title>
    </head>
    <body>
        <button onclick="createCookie()">Set Cookie</button>
        <button onclick="readCookies()">Read Cookies</button>
        <button onclick="deleteCookie()">Delete Cookie</button>
        <p id="output"></p>

        <script>
            function createCookie() {
                document.cookie = "username=JohnDoe; expires=Fri, 31 Dec 2024 23:59:59 GMT; path=/";
                document.getElementById("output").textContent = "Cookie created: username=JohnDoe";
            }

            function readCookies() {
                document.getElementById("output").textContent = "All cookies: " + document.cookie;
            }

            function deleteCookie() {
                document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/";
                document.getElementById("output").textContent = "Cookie deleted: username";
            }
        </script>
    </body>
</html>

Key Takeaways

  • Cookie Management: Use document.cookie to create, read, and delete cookies.
  • Attributes: Add attributes like expires and path to control cookie behavior.
  • Data Persistence: Cookies allow storing small amounts of data on the client-side for session or preference management.
  • Security: Be cautious when handling sensitive data in cookies; consider using Secure and HttpOnly flags.