2

I'm working with a cookie, setting other code varibles using the value of the cookie.

I have defined data about the default state of the cookie as so:

const Cookie = {
  config: {
    name: 'Test_Cookie',
    expire: 1,
    value: true,
  },
...
}

When criteria are met, the cookie gets set for the first time, using this.config.value to set the value of the cookie to true:

  setCookie: function () {
    if (!this.isCookieSet()) {
      $.cookie(this.config.name, this.config.value, this.config.expire);
    }
  },

However, I am finding when I return the cookie value in the code I get "true" back as a string rather than just true. For example (name changed in above example for simplicity):

enter image description here

If I try to do a comparison on the value of the cookie, and use === true I get a false result. If I do === "true" then I get a true result:

showStuff = $.cookie('Test_Cookie') === "true"; // showStuff = true;

OR

showStuff = $.cookie('Test_Cookie') === true; // showStuff = false;

Why does the variable type of the cookie value change when set?

user1486133
  • 1,309
  • 3
  • 19
  • 37

2 Answers2

4

Cookies are strings. You'll need to convert the cookie value to the type you want. The boolean values are being saved as true or false because that's the string representation of a boolean.

You can use the following.

var myBool = Boolean($.cookie('Test_Cookie'));

or

var myBool = ($.cookie('Test_Cookie') === "true");

EDIT As suggested in the first comment by @DelightedD0D:

You could also try - $.cookie('Test_Cookie') === "true"

Sooraj
  • 9,717
  • 9
  • 64
  • 99
  • 1
    Yeah, but be careful, this could act unexpectedly, [see this answer](http://stackoverflow.com/a/264037/1376624). Pobably best just to check for `$.cookie('Test_Cookie') === "true"` – Wesley Smith Sep 06 '16 at 12:59
  • Don't use Boolean() in this case because: `Boolean('false') === true` – Will Apr 12 '22 at 00:34
2

For future readers: You can check against the string value as noted in other answers or convert it to a Boolean value for greater flexibility.

function stringToBoolean(string) {
  switch(string.toLowerCase()) {
    case "false": case "no": case "0": case "": return false;
    default: return true;
  }
}

const isTrue = stringToBoolean("true");
const isFalse = !isTrue;

ref: How can I convert a string to boolean in JavaScript?

darcher
  • 3,052
  • 3
  • 24
  • 29