Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

boolean in an if statement

People also ask

Can you use a boolean in an if statement?

The if statement has the following syntax: if ( condition ) statement; if is a Java reserved word The condition must be a boolean expression. It must evaluate to either true or false.

How do you set a boolean value in if condition?

The if statement will evaluate whatever code you put in it that returns a boolean value, and if the evaluation returns true, you enter the first block. Else (if the value is not true, it will be false, because a boolean can either be true or false) it will enter the - yep, you guessed it - the else {} block.

Can you use == with Booleans?

Boolean values are values that evaluate to either true or false , and are represented by the boolean data type. Boolean expressions are very similar to mathematical expressions, but instead of using mathematical operators such as "+" or "-", you use comparative or boolean operators such as "==" or "!".


First off, the facts:

if (booleanValue)

Will satisfy the if statement for any truthy value of booleanValue including true, any non-zero number, any non-empty string value, any object or array reference, etc...

On the other hand:

if (booleanValue === true)

This will only satisfy the if condition if booleanValue is exactly equal to true. No other truthy value will satisfy it.

On the other hand if you do this:

if (someVar == true)

Then, what Javascript will do is type coerce true to match the type of someVar and then compare the two variables. There are lots of situations where this is likely not what one would intend. Because of this, in most cases you want to avoid == because there's a fairly long set of rules on how Javascript will type coerce two things to be the same type and unless you understand all those rules and can anticipate everything that the JS interpreter might do when given two different types (which most JS developers cannot), you probably want to avoid == entirely.

As an example of how confusing it can be:

var x;

x = 0;
console.log(x == true);   // false, as expected
console.log(x == false);  // true as expected

x = 1;
console.log(x == true);   // true, as expected
console.log(x == false);  // false as expected

x = 2;
console.log(x == true);   // false, ??
console.log(x == false);  // false 

For the value 2, you would think that 2 is a truthy value so it would compare favorably to true, but that isn't how the type coercion works. It is converting the right hand value to match the type of the left hand value so its converting true to the number 1 so it's comparing 2 == 1 which is certainly not what you likely intended.

So, buyer beware. It's likely best to avoid == in nearly all cases unless you explicitly know the types you will be comparing and know how all the possible types coercion algorithms work.


So, it really depends upon the expected values for booleanValue and how you want the code to work. If you know in advance that it's only ever going to have a true or false value, then comparing it explicitly with

if (booleanValue === true)

is just extra code and unnecessary and

if (booleanValue)

is more compact and arguably cleaner/better.

If, on the other hand, you don't know what booleanValue might be and you want to test if it is truly set to true with no other automatic type conversions allowed, then

if (booleanValue === true)

is not only a good idea, but required.


For example, if you look at the implementation of .on() in jQuery, it has an optional return value. If the callback returns false, then jQuery will automatically stop propagation of the event. In this specific case, since jQuery wants to ONLY stop propagation if false was returned, they check the return value explicity for === false because they don't want undefined or 0 or "" or anything else that will automatically type-convert to false to also satisfy the comparison.

For example, here's the jQuery event handling callback code:

ret = ( specialHandle || handleObj.handler ).apply( matched.elem, args );

if ( ret !== undefined ) {
     event.result = ret;
     if ( ret === false ) {
         event.preventDefault();
         event.stopPropagation();
     }
 }

You can see that jQuery is explicitly looking for ret === false.

But, there are also many other places in the jQuery code where a simpler check is appropriate given the desire of the code. For example:

// The DOM ready check for Internet Explorer
function doScrollCheck() {
    if ( jQuery.isReady ) {
        return;
    }
    ...

If you write: if(x === true) , It will be true for only x = true

If you write: if(x) , it will be true for any x that is not: '' (empty string), false, null, undefined, 0, NaN.


In the plain "if" the variable will be coerced to a Boolean and it uses toBoolean on the object:-

    Argument Type   Result

    Undefined       false
    Null            false
    Boolean         The result equals the input argument (no conversion).
    Number          The result is false if the argument is +0, −0, or NaN;
                    otherwise the result is true.
    String          The result is false if the argument is the empty 
                    String (its length is zero); otherwise the result is true.
    Object          true.

But comparison with === does not have any type coercion, so they must be equal without coercion.

If you are saying that the object may not even be a Boolean then you may have to consider more than just true/false.

if(x===true){
...
} else if(x===false){
....
} else {
....
}

It depends on your usecase. It may make sense to check the type too, but if it's just a flag, it does not.


In general, it is cleaner and simpler to omit the === true.

However, in Javascript, those statements are different.

if (booleanValue) will execute if booleanValue is truthy – anything other than 0, false, '', NaN, null, and undefined.

if (booleanValue === true) will only execute if booleanValue is precisely equal to true.


The identity (===) operator behaves identically to the equality (==) operator except no type conversion is done, and the types must be the same to be considered equal.