JavaScript Cookie Operations: Complete Guide to Creation and Reading

Nov 20, 2025 · Programming · 11 views · 7.8

Keywords: JavaScript | Cookie | Web Development | Client-side Storage | User Session

Abstract: This article provides a comprehensive guide to creating and reading cookies in JavaScript. It covers the fundamental concepts, working principles, and practical applications of cookies, presenting two implementation approaches: traditional functional methods and modern ES6 techniques. The article includes complete code examples, parameter explanations, error handling mechanisms, and best practice recommendations to help developers master cookie manipulation techniques.

Basic Concepts and Working Principles of Cookies

Cookies are small text files stored on the user's computer, used for persistently storing user information on the client side. When a user visits a web page, the server can use cookies to "remember" user-related data such as usernames and preferences. Cookies are stored as key-value pairs in the format name=value, with multiple cookies separated by semicolons.

Implementation Methods for Creating Cookies

In JavaScript, cookies can be created using the document.cookie property. Below are two different implementation approaches:

Traditional Functional Implementation

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

This function accepts three parameters: cookie name, value, and expiration days. When days are specified, it calculates the corresponding expiration time; otherwise, the cookie will be deleted when the browser closes. path=/ ensures the cookie is available across the entire website.

Modern ES6 Implementation

const setCookie = (name, value, days = 7, path = '/') => {
  const expires = new Date(Date.now() + days * 864e5).toUTCString()
  document.cookie = name + '=' + encodeURIComponent(value) + '; expires=' + expires + '; path=' + path
}

This implementation uses arrow functions and default parameters, making the code more concise. encodeURIComponent encodes the value to ensure proper handling of special characters. 864e5 represents the number of milliseconds in a day (24 * 60 * 60 * 1000).

Implementation Methods for Reading Cookies

Reading specific cookies requires parsing the document.cookie string. Below are two corresponding reading methods:

Traditional Parsing Method

function getCookie(c_name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) {
                c_end = document.cookie.length;
            }
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return "";
}

This method locates the target cookie through string search, using indexOf to find the name and semicolon positions, then extracts the corresponding value. unescape is used to decode URL-encoded characters.

Modern Array Processing Method

const getCookie = (name) => {
  return document.cookie.split('; ').reduce((r, v) => {
    const parts = v.split('=')
    return parts[0] === name ? decodeURIComponent(parts[1]) : r
  }, '')
}

This implementation uses split and reduce methods, splitting the cookie string into an array and then iterating to find the target. decodeURIComponent decodes URL-encoded values.

Practical Applications of Cookie Operations

Cookies are commonly used for user identification, preference storage, and other scenarios. For example, they can implement user login status persistence, language preference memory, shopping cart content saving, and more. In practical applications, attention should be paid to cookie size limits (typically 4KB), security considerations (using HttpOnly and Secure flags), and privacy compliance requirements.

Best Practices and Considerations

When using cookies, it is recommended to follow these best practices: encrypt sensitive data, set appropriate expiration times, use path and domain parameters to control cookie scope, and consider using localStorage or sessionStorage as alternatives. Additionally, be aware of browser limitations on cookie numbers and cross-domain access restrictions.

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.