Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Check if cookie exists

I have trying to see if a cookie exists or not, Here is my getCookie method:

function getCookie(name)
    {
        var value = "; " + document.cookie;
        var parts = value.split("; " + name + "=");
        if (parts.length == 2) return parts.pop().split(";").shift();
    }

and here is how I calling that method:

var cookie = getCookie("counter");

and here is my condition I tried:

if(cookie == '')
        {
        }
        else
        {
             //Always goes here even when I clear my cookies and I know it does not exist.
        }

My condition always goes into the else, not matter what, what am I doing wrong?

like image 281
user979331 Avatar asked Dec 12 '25 13:12

user979331


1 Answers

You can check the value of cookie if not undefined

    if (typeof(cookie)  === 'undefined'){
     CONSOLE.LOG('no cookie');
    } else {
     CONSOLE.LOG(' cookie exist');
    }
like image 180
Nishant Nair Avatar answered Dec 15 '25 16:12

Nishant Nair