Complete Guide to JavaScript Cookie Operations: Updating and Deleting

Nov 27, 2025 · Programming · 13 views · 7.8

Keywords: JavaScript | Cookie Operations | Web Development

Abstract: This article provides an in-depth exploration of cookie update and deletion mechanisms in JavaScript. By analyzing the fundamental characteristics of cookies, it explains how to update cookie values through overwriting and implement deletion by setting expiration times. The article includes complete functional implementations and discusses cookie security and best practices.

Fundamental Concepts and Working Mechanism of Cookies

In web development, cookies are small text files stored in the user's browser, used to maintain session state and user preferences on the client side. Understanding cookie update and deletion mechanisms requires first clarifying their core characteristics: cookies are essentially key-value pairs transmitted between server and client through HTTP headers. After receiving instructions to set cookies, the browser stores them locally and automatically carries them in subsequent requests.

The Nature of Cookie Updates: Overwriting Instead of Modifying

Many developers mistakenly believe that cookies support direct update operations, but in reality, cookie updates are achieved through complete overwriting. When needing to modify a cookie's value, you must reset the cookie using the same name, where the new value completely replaces the old value. This design stems from the stateless nature of the HTTP protocol, as browsers do not provide direct cookie modification interfaces.

Below is a complete cookie operation function library demonstrating how to implement cookie creation, reading, updating, and deletion:

function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    } else {
        var expires = "";
    }
    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1, c.length);
        }
        if (c.indexOf(nameEQ) == 0) {
            return c.substring(nameEQ.length, c.length);
        }
    }
    return null;
}

function updateCookie(name, newValue, days) {
    createCookie(name, newValue, days);
}

function eraseCookie(name) {
    createCookie(name, "", -1);
}

Implementation Principle of Cookie Deletion

Similar to update operations, cookie deletion does not actually remove data from browser storage but is achieved by setting the expiration time to a point in the past. When the browser detects that a cookie has expired, it automatically removes it from storage. This mechanism ensures uniformity in cookie management, as all operations are completed by setting new cookie values.

In the eraseCookie function, by setting the expiration time to -1 day (i.e., a past time), the browser automatically deletes the cookie during the next validity check. The advantage of this method is excellent compatibility, working reliably across all modern browsers.

Analysis of Practical Application Scenarios

Consider a typical user login system scenario: when a user logs in for the first time, the system uses createCookie("username", "John", 30) to create a cookie valid for 30 days. If the user updates personal information and needs to change the username, call updateCookie("username", "JohnSmith", 30). When the user logs out, call eraseCookie("username") to clear the login status.

Security and Best Practices

Cookie operations involve user privacy and data security. Developers need to pay attention to the following points: First, sensitive information should not be stored directly in cookies; consider using server-side sessions instead. Second, set appropriate path and domain restrictions to prevent accidental access to cookies. Finally, for cookies involving user authentication, use HTTPS protocol for transmission and set HttpOnly and Secure flags.

The article also discusses the essential differences between HTML tags like <br> and character \n, requiring proper distinction between display formatting and control characters in text processing. This understanding helps avoid encoding issues when handling cookie values.

Browser Compatibility Considerations

Although the above code performs well in modern browsers, additional handling may be required in some older browser versions. Particularly for date format processing and special character encoding, it's recommended to add appropriate compatibility checks in actual projects. Furthermore, with the popularity of Web Storage API, for large data storage needs, consider prioritizing localStorage and sessionStorage.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.