0

I am trying to set a cookie-value for somebody who visits my index-page with cookie.js like so:

<script src="https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"></script>

<script> 
  var index_da = Cookies.get('sw_home_visit');

    if (index_da < 1) {
        Cookies.set('sw_home_visit', '1', {
            expires: 365
        });
        console.log("nicht da")
    } else {
        console.log("da")
    }
</script>

As I get printed "da" all the time in my console this can have several reasons I guess; is this then right or what do I need to correct?

Daiaiai
  • 1,019
  • 3
  • 12
  • 28

1 Answers1

2
Cookies.get('sw_home_visit');

This line returns undefined because the cookie does not exist. undefined < 1 is always false. Change your code in something like :

Cookies.get('sw_home_visit') || 0;

If the cookie does not exist, the value will be 0 and the cookie will be created. Or change your if condition to handle undefined results.

Junior Dussouillez
  • 2,327
  • 3
  • 30
  • 39
  • Thanks. I already it'd be something like that. So Cookies.get('sw_home_visit') || 0; sets the value of "Cookies" to 0? But is it then using the real "value" of the Cookie-variable at all? – Daiaiai Jan 22 '18 at 13:00
  • 1
    @Daiaiai `Cookies.get('sw_home_visit') || 0` evaluates to `Cookies.get('sw_home_visit')` or, if it’s `undefined` or any other falsy value, to `0`. See [JavaScript OR (||) variable assignment explanation](https://stackoverflow.com/q/2100758/4642212). – Sebastian Simon Jan 22 '18 at 13:11