JavaScript and Cookies

Hello there, future JavaScript wizards! Today, we're going to embark on a delicious journey into the world of cookies. No, not the kind you dunk in milk (though I wouldn't mind one of those right now), but the digital kind that makes our web experiences smoother and more personalized. So, grab your virtual apron, and let's start baking... I mean, coding!

JavaScript - Cookies

What are Cookies?

Cookies are small pieces of data stored on a user's computer by websites they visit. Think of them as little digital Post-it notes that websites stick on your computer to remember things about you. These "notes" can contain various bits of information, like your preferences, login details, or items in your shopping cart.

When I first learned about cookies, I imagined tiny computer elves scribbling notes and stuffing them into my PC. While that's not quite how it works, it's not a bad way to visualize the concept!

Why are Cookies needed?

You might be wondering, "Why can't websites just remember stuff without these cookie things?" Well, let me tell you a little story.

Imagine you're at a busy cafe. You order a coffee and a sandwich, but then you need to use the restroom. When you come back, how does the barista know which order is yours among the sea of customers? That's where cookies come in handy in the digital world.

Cookies are needed for several reasons:

  1. Remembering user preferences
  2. Keeping users logged in
  3. Tracking items in shopping carts
  4. Personalizing user experiences
  5. Analyzing user behavior for improvements

Without cookies, every time you visited a website, it would be like meeting for the first time - no memory of your preferences, no saved login, no items in your cart. Not very convenient, right?

How It Works?

Now, let's peek under the hood and see how these digital cookies actually work. Don't worry; it's not as complicated as it might sound!

When you visit a website, it can send a cookie to your browser. Your browser then stores this cookie on your computer. The next time you visit the same website, your browser sends the cookie back to the website. It's like a secret handshake between your computer and the website.

Here's a simple diagram of how it works:

User visits website
        ↓
Website sends cookie
        ↓
Browser stores cookie
        ↓
User revisits website
        ↓
Browser sends cookie
        ↓
Website recognizes user

Now that we understand the basics, let's roll up our sleeves and start working with cookies in JavaScript!

Setting/Storing Cookies

Setting a cookie is like leaving a note for later. In JavaScript, we use the document.cookie property to create a cookie. Here's how you can do it:

document.cookie = "username=John Doe";

Let's break this down:

  • document.cookie is the property we use to interact with cookies.
  • "username=John Doe" is the actual cookie. It's a key-value pair, where username is the key and John Doe is the value.

You can also set multiple cookies:

document.cookie = "username=John Doe";
document.cookie = "age=30";
document.cookie = "city=New York";

Each document.cookie statement creates a new cookie. It doesn't overwrite the existing ones.

Reading Cookies

Reading cookies is like rifling through those notes you left for yourself. Here's how you can read cookies:

let allCookies = document.cookie;
console.log(allCookies);

This will give you all the cookies as one long string. But usually, you want to get a specific cookie value. Here's a function to do that:

function getCookie(name) {
    let cookieArr = document.cookie.split(";");

    for(let i = 0; i < cookieArr.length; i++) {
        let cookiePair = cookieArr[i].split("=");

        if(name == cookiePair[0].trim()) {
            return decodeURIComponent(cookiePair[1]);
        }
    }

    return null;
}

// Usage
let username = getCookie("username");
console.log(username); // Outputs: John Doe

This function splits the cookie string, loops through each cookie, and returns the value if it finds a match.

Setting Cookies Expiry Date

Cookies are like milk - they can go bad if left out too long. By default, cookies expire when the browser session ends. But you can set a specific expiry date:

let expiryDate = new Date();
expiryDate.setMonth(expiryDate.getMonth() + 1);

document.cookie = "username=John Doe; expires=" + expiryDate.toUTCString();

This cookie will expire in one month. The expires attribute tells the browser when to delete the cookie.

Deleting a Cookie

Sometimes, you need to throw away a cookie. To delete a cookie, you set its expiry date to a past date:

document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";

This sets the cookie's value to empty and its expiry date to a time in the past, effectively deleting it.

Updating Cookies

Updating a cookie is as simple as setting it again with a new value:

document.cookie = "username=Jane Doe";

If a cookie with the name "username" already exists, this will update its value. If it doesn't exist, it will create a new cookie.

Cookie Methods Table

Here's a handy table summarizing the methods we've learned:

Action Method
Set Cookie document.cookie = "key=value";
Read All Cookies let allCookies = document.cookie;
Read Specific Cookie Use getCookie() function
Set Expiry document.cookie = "key=value; expires=date";
Delete Cookie Set expiry to past date
Update Cookie Set cookie again with new value

And there you have it, folks! You're now equipped with the knowledge to work with cookies in JavaScript. Remember, with great power comes great responsibility. Always respect user privacy and be transparent about your use of cookies.

Next time you're browsing the web and a site remembers your preferences, you can smile knowingly and think, "Ah, cookies at work!" Happy coding, and may your digital cookies always be fresh and your real cookies always be delicious!

Credits: Image by storyset