Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript booleans: false && true results in true

Tags:

javascript

I need to disable/enable a button depending in on the value of some radio groups. These radios are populated by some groovy code becasue I'm using grails, a framework for groovy, that is a superset of java. Well that explanation was to say that the values of the radios are defined as booleans, which is just natural because they correspond to yes/no answers.

Now, to disable/enable this button I use some javascript, but it goes bananas with boolean values. As the title states, on some point I do a logical and between a variable that holds false and another variable that holds true

Here is the peice of problematic code:

var actual = true;
$('.requerido input:radio:checked').each(function() {
    console.log("actual: " + actual);
    console.log("value: " + this.value);
    console.log("actual and value: " + (actual && this.value));
    actual = actual && this.value;
    console.log("actual: " + actual);
});

As you can see I use the console.log for debugging, and this is what throws at some point:

actual: true
value: true
actual and value: true
actual: true

actual: true
value: false
actual and value: false
actual: false

actual: false
value: true
actual and value: true
actual: true

So true && false == false, but false && true == true ? Note that the values have no quotes, so they are boolean values (I'm debugging using the Chrome console which represent strings inside double quotes, so you can distinguish between true and "true").

Any ideas?

Also, doing a manual comparison like var x = true && false always works as expected, is juts with variables that the problem is present.

like image 354
GalmWing Avatar asked Apr 23 '12 05:04

GalmWing


2 Answers

The this.value from your checked radio button input is not actually a boolean it is a string. The comparison of strings and boolean values can cause issues like this. It is one of the reasons why it is considered best practise is to use === for comparison.

See this SO Question for full details; JavaScript === vs == : Does it matter which “equal” operator I use?

like image 147
Dave Anderson Avatar answered Sep 17 '22 19:09

Dave Anderson


Note that the && does the following:

Returns expr1 if it can be converted to false; otherwise, returns expr2.

source

So in cases like:

var truish=true;//interchangeable with anything different than 0,"",false,null,undefined,NaN
var falsish=null;//interchangeable with 0,"",false,null,undefined,NaN

alert(truish&&falsish);//null (falsish was returned)

The returned value isn't necessarily a boolean, a solution to this would be to force a boolean !(x&&y)

So my guess is that something like this is happening

like image 20
ajax333221 Avatar answered Sep 18 '22 19:09

ajax333221