-2

why do nonzero numbers equate to true if nonzero numbers are truthy?

For example, the following oddly prints.

'c == true is false'

if (c == true) {
 console.log('c == true is true');
} else {
 console.log('c == true is false');
}

To make sure I'm not crazy, I confirmed that c is truthy by running the following code chunk, which prints

'c is true'

if (c) {
 console.log('c is true')
} else {
 console.log('c is false');
}
GNG
  • 997
  • 13
  • 33
  • The number `2` and the boolean value `true` are two different things, so obviously that comparison will evaluate to `false` – UnholySheep May 05 '22 at 19:37
  • 1
    truthy doesn't mean they are equal to `true` but that they convert to `true`. – VLAZ May 05 '22 at 19:37
  • 1
    The coercion isn't `2 == true` -> `true == true`. Instead, it's `2 == true` -> `2 == 1` which is obviously `false`. This is covered in [the ECMAScript docs](https://262.ecma-international.org/8.0/#sec-abstract-equality-comparison) section 7.2.13 step 7. "If `Type(y)` is `Boolean`, return the result of the comparison `x == ToNumber(y)`." – D M May 05 '22 at 19:40
  • 1
    In the comparison `c == true`, `true` is converted to `1` with `Number(true)`, not `2` to `true`. – jabaa May 05 '22 at 19:40
  • You got true and truthy mixed up. You can do `!!c == true` instead. – code May 05 '22 at 19:42

0 Answers0