headacheCoder
headacheCoder

Reputation: 4613

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

Upvotes: 3

Views: 526

Answers (3)

Felix Kling
Felix Kling

Reputation: 816364

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

Upvotes: 2

Nishu Tayal
Nishu Tayal

Reputation: 20830

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

Upvotes: 1

Ry-
Ry-

Reputation: 224906

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.

Upvotes: 3

Related Questions