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.