Based on these rules:
Falsy:
Truthy: Everything else
I fail to find the correct explanation as to why in following tests, only number 1 evaluates to "true"
0 == true ("false")
1 == true ("true")
2 == true ("false")
othernumber == true ("false")
The "truthy" and "falsy" rules only apply when the value itself is being used as the test, e.g.:
var str = "";
if (str) {
// It's truthy
} else {
// It's falsy
}
==
has its own, different, set of rules for determining the loose equality of its operands, which are explained thoroughly in the spec's Abstract Equality Comparison algorithm:
- If Type(x) is the same as Type(y), then
- Return the result of performing Strict Equality Comparison x === y.
- If x is null and y is undefined, return true.
- If x is undefined and y is null, return true.
- If Type(x) is Number and Type(y) is String, return the result of the comparison x == ToNumber(y).
- If Type(x) is String and Type(y) is Number, return the result of the comparison ToNumber(x) == y.
- If Type(x) is Boolean, return the result of the comparison ToNumber(x) == y.
- If Type(y) is Boolean, return the result of the comparison x == ToNumber(y).
- If Type(x) is either String, Number, or Symbol and Type(y) is Object, return the result of the comparison x == ToPrimitive(y).
- If Type(x) is Object and Type(y) is either String, Number, or Symbol, return the result of the comparison ToPrimitive(x) == y.
- Return false.
See the spec for the full details of the various abstract operations listed in there, although the names pretty much say what they do. (If you look at the spec, you'll see !
prior to ToNumber
in various places; I've removed it above. It's not the logical NOT operator, it's a spec notation related to "abrupt completions.")
Let's follow that through for your 2 == true
example:
But notice that step 7 is different for your 1 == true
example:
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