First case (===
):
function checkEqual(a, b) {
return (a === b ? true : false );
}
checkEqual(1, 2);
Here you are using the identity operator (a.k.a. strict equality operator). It checks if the values are equal (and of the same type).
Since a
is 1
and b
is 2
, then a === b
becomes false
(since they are different). And of course false ? true : false
is false
. So, the whole thing returns false
. Yes, you might just do this:
function checkEqual(a, b) {
return a === b;
}
checkEqual(1, 2);
Second case (=
):
function checkEqual(a, b) {
return (a = b ? true : false );
}
checkEqual(1, 2);
Here you are using the assigment operator. This is not an equality or identity check.
In this case, a = b
assigns the value of b
to a
and returns it. So both a
and b
will be 2
, and a = b
evaluates to 2
. Finally, since 2
is a truthy value, 2 ? true : false
is true
.
Note: that also means that if you were to pass a falsy value for b
, you would get false
. For example with the call: checkEqual(1, null);
The value passed to a
is irrelevant.
The case you didn't do (==
):
function checkEqual(a, b) {
return (a == b ? true : false );
}
checkEqual(1, 2);
Here you would be using the equality operator. It checks if the values are equal (however, it is free to convert the values to check).
Similarly to the first one, this will return false
. What is the difference? Well, types. In Javascript "1" == 1
is true
but "1" === 1
is false
. That is, by using ==
you are allowing the runtime to convert the values in order to compare them, but with ===
you are not.
See JavaScript comparison operators: Identity vs. Equality and Which equals operator (== vs ===) should be used in JavaScript comparisons?