Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript truthy numbers

Based on these rules:

Falsy:

  • false
  • 0 (zero)
  • '' or "" (empty string)
  • null
  • undefinded
  • NaN (e.g. the result of 1/0)

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")
like image 412
David Avatar asked Sep 08 '25 13:09

David


1 Answers

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:

  1. If Type(x) is the same as Type(y), then
    • Return the result of performing Strict Equality Comparison x === y.
  2. If x is null and y is undefined, return true.
  3. If x is undefined and y is null, return true.
  4. If Type(x) is Number and Type(y) is String, return the result of the comparison x == ToNumber(y).
  5. If Type(x) is String and Type(y) is Number, return the result of the comparison ToNumber(x) == y.
  6. If Type(x) is Boolean, return the result of the comparison ToNumber(x) == y.
  7. If Type(y) is Boolean, return the result of the comparison x == ToNumber(y).
  8. If Type(x) is either String, Number, or Symbol and Type(y) is Object, return the result of the comparison x == ToPrimitive(y).
  9. If Type(x) is Object and Type(y) is either String, Number, or Symbol, return the result of the comparison ToPrimitive(x) == y.
  10. 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:

  1. The types aren't the same, so keep going
  2. x isn't null, so keep going
  3. x isn't undefined, so keep going
  4. Type(x) is indeed Number, but Type(y) is not String, so keep going
  5. Type(x) is not String, so keep going
  6. Type(x) is not Boolean, so keep going
  7. Type(y) is Boolean, so return the result of x == ToNumber(y)
    • ToNumber(true) is 1, and since 2 == 1 is false, the result is false

But notice that step 7 is different for your 1 == true example:

  1. Type(y) is Boolean, so return the result of x == ToNumber(y)
    • ToNumber(true) is 1, and since 1 == 1 is true, the result is true
like image 53
T.J. Crowder Avatar answered Sep 10 '25 04:09

T.J. Crowder