0

I am missing something really simple...

I have a button that sets a cookie:

<button id="gotit" >Got it</button>

JS:

   $('#gotit').click(function () {
          setCookie("gotIt", 'True', 30);
      });

And I a checkGetIt() function with a simple if else:

 function checkGetIt() {
          var gotIt = getCookie("gotIt");
          if (gotIt === "") {
              console.log('no such cookie'); // should do this until button pressed
          } else {
              console.log('cookie exists'); // this displays all the time, which is wrong
          }
      }
      checkGetIt();
      var z = document.cookie;
   console.log('existing cookies: ' + z);

But I always get console.log('cookie exists'); even if console.log('existing cookies: ' + z); gives me nothing before the button click.

setCookie() and getCookie() are generic functions that worked for me before.

JSFIDDLE here.

Andrejs
  • 10,803
  • 4
  • 43
  • 48

1 Answers1

2

You have a problem in the following line:

if (gotIt === "")

Either change it to:

if (gotIt === null) // This will check for null.

Or:

if (gotIt == null) // This will check for null or undefined.

Further reading: Which equals operator (== vs ===) should be used in JavaScript comparisons?

You should always use "===" (no type conversion) except for checking "undefined or null", in that case, the best way to do it is comparing "== null".

Community
  • 1
  • 1
Charmander
  • 276
  • 3
  • 20
  • Thanks, that works. Can you comment please in what cases if(cookie =="") can work but in some cases it must be (cookie === null)? – Andrejs Aug 13 '15 at 13:01
  • 1
    `null` is when a cookie isn't set. Sometimes a cookie can be set, but to an empty string `""`. – evolutionxbox Aug 13 '15 at 13:02
  • 1
    You were doing if(cookie === ""), which in English language would be "if the cookie variable is an empty string", and as you can see in your getCookie function, you are returning null. Hence, that condition will always return false. For more information, please refer to the link I provided in the answer. If you still have doubts, let us know. – Charmander Aug 13 '15 at 13:05
  • That explains it. Cheers. – Andrejs Aug 13 '15 at 13:06