Reputation: 4073
i am trying to invert a boolean value (toggle);
var current_state=$.cookie('state');
if(current_state==null) {
current_state=false;
}
console.log(current_state);
current_state=(!current_state);
console.log(current_state);
$.cookie('state', current_state, { expires: 7, path: '/' });
In my opinion the second console.log
should display the opposite of the first one, but both calls report false
. Whats up here?
Upvotes: 0
Views: 2296
Reputation: 1495
The problem is that current_state is not a boolean but a string
var current_state=$.cookie('state');
if(current_state==null) {
current_state=false;
}
console.log(current_state);
var current_state= current_state == 'false' ? "true" : "false"; // (!current_state);
console.log(current_state);
$.cookie('state', current_state);
Upvotes: 0
Reputation: 137320
Your $.cookie('state')
seems to be a string ("false
").
As a proof, see the following code (also in this jsfiddle):
var current_state='false';
if(current_state==null) {
current_state=false;
}
console.log(current_state);
var current_state=(!current_state);
console.log(current_state);
It outputs false
twice.
Why? Because you check if it is null and do not support other cases.
You can do something like this:
var current_state='false';
if(current_state==null ||
current_state==false ||
current_state=='false') {
current_state = false;
}else{
current_state = true;
}
console.log(current_state);
current_state=(!current_state);
console.log(current_state);
and your code will output boolean true
or false
first and then the opposite boolean value.
Upvotes: 4
Reputation: 120410
Are you sure that in the case that current_state
is not null
that it is actually a boolean value? Perhaps it's a string?
Upvotes: 3