When evaluated as a test condition, integers like -1, 5 and 17,000,000, all return Boolean true, because they logically evaluate to true, e.g.
if(-1) {
"This is true";
}
else {
"This is false";
}
=> "This is true";
(Note: 0 logically evaluates to false)
Using the "?" operator does what this code just does. It passes the first argument as a condition in an if statement, passes the second argument as the true case, and passes the third argument as the false case.
Hence the third result.
However, these integers are not of the same type as true.
True is of type Boolean, -1, 5 and 17,000,000 are of type Integer.
The comparison '==' is strict, in terms of type comparison. Even two things have the same "value", but not the same type, the "==" operator returns false:
if(6 == true) {
"This is true";
}
else {
"This is false";
}
=> "This is false";
Even the following will return false, because "true" is of type String and true is of type Boolean:
if("true" == true) {
"This is true";
}
else {
"This is false";
}
=> "This is false";
Hence, the first two results.
Note: If you'd like to compare values irregardless of type, use the "===" operator:
if(6 === true) {
"This is true";
}
else {
"This is false";
}
=> "This is true";
and also,
if("true" === true) {
"This is true";
}
else {
"This is false";
}
=> "This is true";
Hope this helps!
how can -1 be === to a bool?
It can't, but using the type-safe comparison you'll don't have to worry about thesloppy equals
. – Hanshaw