3

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)?

headacheCoder
  • 4,503
  • 8
  • 30
  • 33
  • Yes, they're different. It's been discussed several times on SO. –  Jun 20 '12 at 17:45
  • Yes. See these two related questions: http://stackoverflow.com/questions/7496727/why-does-0-a-b-behave-different-than-0-true-a-b and http://stackoverflow.com/questions/5791158/javascript-what-is-the-difference-between-if-x-and-if-x-null – Felix Kling Jun 20 '12 at 17:45

3 Answers3

3

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.

Ry-
  • 218,210
  • 55
  • 464
  • 476
2

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).

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
1

Yeah, there is a huge difference in both if(myVar) and if(!myVar) and if(myVar == true) and if(myVar == false)

In if(myVar) and if(!myVar) , !myVar will return true for every "false" value (empty string, 0, null, false, undefined, NaN)

while if(myVar == true) and if(myVar == false) check whether myVar value is true or false. Even if myVar value is NULL, NaN or undefined 0, it'll compare like

if(NULL == true)

Summing up :

NOT operator'!' converts a value into its opposite boolean equivalent. This is different than actually comparing two values.
And if you compare values with '==', JavaScript does type conversion which can lead to unexpected behavior (like undefined == null).
Nishu Tayal
  • 20,106
  • 8
  • 49
  • 101