JavaScript's conditional operators such as if-else
and a ? b : c
don't require the condition to be of actual Boolean
type but rather check whether it is truthy
or a falsy
value in JavaScript terms.
For example, such values as null
and 0
are considered falsy
so they would be treated like false
in if-else
and ternary operators.
In a broader sense this might be considered as a case of type coercion, see for example this question for more information. So when an interpreter sees non-boolean expression inside an if
it is "re-writing" it like if (Boolean("string")) { ... }
, i.e. invoking conversion from the expression to the exact boolean type.