I know the difference between ==
and ===
however I always believed that if (condition)
condition
was supposed to be evaluated against true
using strict equality (===
) and not type-coercing equality (==
).
See an example:
if (1) {
console.log("1");
}
if (1 == true) {
console.log("2");
}
if (1 === true) {
console.log("3");
}
It returns:
::1
::2
I know 1 is not strictly equal to true
, because the type is different, but when I do if (condition)
according to W3C it should be the strict equality test (===
) that is run not the type-coercing equality of ==
.
So why is it logging 1?
The if
statement uses condition == true
. It's given in the ECMAScript Language Specification, here: http://www.ecma-international.org/ecma-262/5.1/#sec-12.5
Note the usage of the ToBoolean()
in Step 2. This converts the given argument to a Boolean value, meaning that yes, type coercion does occur for the condition of an if
statement.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With