0

I noticed this behavior in Javascript today which has me thoroughly surprised and confused:

if ("0") {
    console.log('first')
}
if ("0" == true) {
    console.log('second');
}

output:

first

I would have expected either both or neither of the console.log lines to execute. I had always believed that the contents of a guard is evaluated, coerced into a boolean, and then passes or fails based on the value of this boolean. This would result in both of the guards above being equivalent, but the observed behavior indicates something else is going on.

How does Javascript determine whether a guard passes or fails?

DNKROZ
  • 2,634
  • 4
  • 25
  • 43
Mala
  • 14,178
  • 25
  • 88
  • 119
  • 2
    `== true` does not coerce to a boolean, it coerces both parts to a number. – Bergi May 21 '17 at 20:30
  • 1
    Only `Boolean(…)` is equivalent to `Boolean(…) == true` – Bergi May 21 '17 at 20:31
  • @Bergi: why do both parts get coerced into a number if neither is a number to begin with? – Mala May 21 '17 at 20:32
  • Because numbers are a good middle way? I don't know, that's just how it works. If you don't want coercion but just fail to `false` for different types, use `===`. – Bergi May 21 '17 at 20:34
  • So `==` in Javascript always coerces both sides into a number regardless of their types? Or is it just because one of the sides was "number-like"? – Mala May 21 '17 at 20:35
  • I was only referring to the case where one of the operands is a boolean. You can read the full algorithm [here](http://es5.github.io/#x11.9.3) – Bergi May 21 '17 at 20:40

0 Answers0