Search code examples
javascriptif-statementequalityequals-operator

Why does an assignment in an if statement equate to true?


Let me start off by saying I understand the difference between =, ==, and ===. The first is used to assign the right-hand value to the left-hand variable, the second is used to compare the equivalency of the two values, and the third is used not just for equivalency but type comparison as well (ie true === 1 would return false).

So I know that almost any time you see if (... = ...), there's a pretty good chance the author meant to use ==.

That said, I don't entirely understand what's happening with these scripts:

var a = 5;

if (a = 6)
	console.log("doop");

if (true == 2)
	console.log('doop');

According to this Javascript type equivalency table, true is equivalent to 1 but not 0 or -1. Therefore it makes sense to me that that second script does not output anything (at least, it isn't in my Chrome v58.0.3029.110).

So why does the first script output to the console but the second doesn't? What is being evaluated by the first script's if statement?

I dug into my C# knowledge to help me understand, but in C# you cannot compile if (a = 5) Console.WriteLine("doop"); so I had to explicitly cast it to a bool by doing if (Convert.ToBoolean(a = 5)) but then that makes sense it would evaluate to true because according to MSDN's documentation, Convert.ToBool returns true if the value supplied is anything other than 0. So this didn't help me very much, because in JS only 1 and true are equal.


Solution

  • There's a difference between making an abstract equality comparison with == and performing a simple type cast to boolean from a number value. In a == comparison between a boolean and a number, the boolean value is converted to 0 or 1 before the comparison. Thus in

    if (true == 2)
    

    the value true is first converted to 1 and then compared to 2.

    In a type cast situation like

    if (x = 2)
    

    the number is converted to boolean such that any non-zero value is true. That is, the value 2 is assigned to x and the value of the overall expression is 2. That is then tested as boolean as part of the evaluation of the if statement, and so is converted as true, since 2 is not 0.

    The various values that evaluate to boolean false are 0, NaN, "", null, undefined, and of course false. Any other value is true when tested as a boolean (for example in an if expression).