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)?
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:
So
trueis converted to a number first and latermyVarwill be converted to a number as well.If you only have
if(myVar)though, then the value is converted to a boolean:ToNumber[spec] andToBoolean[spec] can return very different results.Note: If
myVaris actually a boolean, then there is no difference betweenif(myVar == true)andif(myVar).