JavaScript Cookies Practice Solution

Understanding the Problem

We need to implement browser cookie functionality to persist user preferences across browser sessions. The key requirements are:

Input:

Output:

Devising a Plan

  1. Implement theme storage using cookies that persist across browser sessions
  2. Create functions to store and retrieve theme preferences
  3. Implement clearing functionality for theme cookies
  4. Add display name storage using session cookies
  5. Ensure proper cookie parsing when multiple cookies exist

Complete Solution


// Cookie utility function to get a specific cookie value
function getCookie(name) {
    // Convert cookie string to array of individual cookies
    const cookies = document.cookie.split('; ');
    
    // Find the specific cookie we want
    const cookieEntry = cookies.find(cookie => cookie.startsWith(name + '='));
    
    // Return just the value portion if found, otherwise null
    return cookieEntry ? decodeURIComponent(cookieEntry.split('=')[1]) : null;
}

// Phase 1 & 2: Theme Functions
function storeTheme(themeName) {
    // Set cookie with 24 hour expiration for persistence
    const expirationDays = 1;
    const expirationDate = new Date();
    expirationDate.setDate(expirationDate.getDate() + expirationDays);
    
    // Format cookie with name=value;expires=date
    document.cookie = `themeName=${themeName};expires=${expirationDate.toUTCString()};path=/`;
}

function restoreTheme() {
    const savedTheme = getCookie('themeName');
    if (savedTheme) {
        setTheme(savedTheme);
    }
}

function clearTheme() {
    // Set expiration to past date to remove cookie
    document.cookie = 'themeName=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/';
}

// Phase 3: Display Name Functions
function storeName(displayName) {
    // Store as session cookie (no expiration date)
    document.cookie = `displayName=${encodeURIComponent(displayName)};path=/`;
}

function restoreName() {
    const savedName = getCookie('displayName');
    if (savedName) {
        setInputValue('display-name', savedName);
    }
}

function clearName() {
    // Set expiration to past date to remove cookie
    document.cookie = 'displayName=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/';
}
    

Code Explanation

Cookie Utility Function

The getCookie utility function solves a key challenge when working with multiple cookies. Think of document.cookie like a cookie jar - when you look inside, all cookies are mixed together. This function helps us find the specific cookie we want:


function getCookie(name) {
    const cookies = document.cookie.split('; ');
    const cookieEntry = cookies.find(cookie => cookie.startsWith(name + '='));
    return cookieEntry ? decodeURIComponent(cookieEntry.split('=')[1]) : null;
}
    

This function:

  1. Splits the cookie string at semicolons to get individual cookies
  2. Finds the specific cookie that starts with our desired name
  3. Extracts and decodes just the value portion

Theme Storage Functions

The theme storage implements persistent cookies that survive browser restarts:


function storeTheme(themeName) {
    const expirationDays = 1;
    const expirationDate = new Date();
    expirationDate.setDate(expirationDate.getDate() + expirationDays);
    document.cookie = `themeName=${themeName};expires=${expirationDate.toUTCString()};path=/`;
}
    

This creates a cookie that:

Display Name Functions

The display name uses session cookies that clear when the browser closes:


function storeName(displayName) {
    document.cookie = `displayName=${encodeURIComponent(displayName)};path=/`;
}
    

Notice the lack of an expiration date - this makes it a session cookie.

Real World Applications

Cookie management like this is commonly used for:

Testing Strategy

To thoroughly test this implementation:

Theme Testing

  1. Select a theme and refresh the page (should persist)
  2. Close and reopen browser (should persist for 24 hours)
  3. Wait 24 hours and refresh (should reset to default)
  4. Test clear functionality

Display Name Testing

  1. Enter name and refresh (should persist)
  2. Close tab and reopen (should persist)
  3. Close browser and reopen (should reset)
  4. Test with special characters (should handle properly)

Common Pitfalls and Solutions

When working with cookies, watch out for:

Cookie String Format

Cookies must be properly formatted with name=value pairs and semicolon separators. Common issues include:

Multiple Cookies

When multiple cookies exist, you need proper parsing logic to extract specific values. Our getCookie helper function handles this cleanly.

Security Considerations

While this implementation is safe for preferences, remember: