Scorpiorian83
Scorpiorian83

Reputation: 479

Can you explain to me about this line of code for Javascript cookie tutorial?

I'm just beginning to learn javascript and while I was going through the cookie tutorial, there is a part which I don't understand at all. Can you guys please explain it to me in detail? Thanks in advance!

Below's the whole script but the only part which puzzles me is the readCookie(name) function. The first line var nameEQ = name + "="; I don't understand why we have to put an equal sign to the end of the string.

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 eraseCookie(name) {
    createCookie(name,"",-1);
}

Upvotes: 0

Views: 55

Answers (2)

miln
miln

Reputation: 135

There are more details here (MDN), but briefly...

At minimum, a cookie is a string that consists of the name of the cookie (the part before the equal sign) and the value of the cookie (the part after the equal sign). So, the equal sign is just the divider between name and value. This way the cookie can be stored as a string but contain multiple parts.

Since that function is searching through all cookies, you need the name plus the equal sign to find the correct value. Without the equal sign, you may get the wrong cookie that has the name you are looking for in its value.

Upvotes: 1

JanR
JanR

Reputation: 6130

At first glance:

In this line: if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);

it is looking for "name=" and if it finds it removes it from the string. It appends the = to ensure it strips the whole section from string c.

Example: say c = name=SomeCookieName, after that line of code you will be left with SomeCookieName

Upvotes: 2

Related Questions