Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript If/Else Conditions & Comparisons - Differences

Okay, here's my short question:

I know that === and !== operators will compare the types and then the values, and that == and != will cast the types and then just compare the values.

What about if(myVar) and if(!myVar)?

Is there any difference in the behavior from if(myVar == true) and if(myVar == false)?

like image 654
headacheCoder Avatar asked Nov 24 '25 17:11

headacheCoder


2 Answers

Yes, there is a difference. For example:

if('true' == true) {
    alert("This doesn't happen");
}

if('true') {
    alert("But this does happen.");
}

The reason? They're both converted to numbers for comparison. 'true' is converted to NaN and true is converted to 1.

Avoid this silliness and never write == true or == false.

like image 154
Ry- Avatar answered Nov 27 '25 07:11

Ry-


Yes, there is a difference. As you already mentioned, if you compare a value with ==, type conversion takes places.

If the values are not of the same type, they will both be converted to either strings or numbers. If one of the values is a boolean and the other is not, both values will be converted to numbers.

The comparison algorithm is defined in section 11.9.3 of the specification. The important step is here:

7. If Type(y) is Boolean, return the result of the comparison x == ToNumber(y).

So true is converted to a number first and later myVar will be converted to a number as well.


If you only have if(myVar) though, then the value is converted to a boolean:

2. If ToBoolean(GetValue(exprRef)) is true, then


ToNumber [spec] and ToBoolean [spec] can return very different results.


Note: If myVar is actually a boolean, then there is no difference between if(myVar == true) and if(myVar).

like image 29
Felix Kling Avatar answered Nov 27 '25 06:11

Felix Kling



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!