user1486133 user1486133 - 3 months ago 12
jQuery Question

jQuery cookie sets boolean value as string

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?

Answer

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"