<-- Storage code samples

Cookie code samples

This code consists of two functions to manipulate cookies; a setCookie() and a getCookie() function.


function setCookie(cookieName, cookieValue, expirationDays) {
    var expirationDate = new Date();
    expirationDate.setDate(expirationDate.getDate() + expirationDays);
    cookieValue = cookieValue + '; expires=' + expirationDate.toUTCString();
    document.cookie = cookieName + '=' + cookieValue;
}

function getCookie(cookieName) {
    var cookies = document.cookie.split(';');

    for (let cookie of cookies) {
        let index = cookie.indexOf('=');
        let key = cookie.substr(0, index);
        let val = cookie.substr(index + 1);

        if (key.trim() === cookieName) { return val; }
    }
}
    

Index of namespace patterns

The original code pollutes the global namespace so here are examples of the same two cookie functions wrapped in different namespace patterns for organization, reuse, and encapsulation

  1. Single global variable - a-cookie1-global-var.html
  2. Object literal notation - a-cookie2-literal-notation.html
  3. Nested namespace pattern - a-cookie3-nested-namespace.html
  4. Immediately Invoked Function Expression (IIFE) - a-cookie4-iife-wrapped.html

Web Storage