Do you know what will be the output of this code?
JavaScript
const isTrue = true == [];
const isFalse = true == ![];
console.log(isTrue + isFalse);
Show answer and explanation
Let’s break this up. The comparison performed is the abstract comparison operation, which uses type coercion under the hood, when necessary.
As the first parameter is a boolean, the following rule applies: “If Type(x) is Boolean, return the result of the comparison ToNumber(x) == y.” And in the next round, the next rule applies: “If Type(y) is Boolean, return the result of the comparison x == ToNumber(y).”
Which then boils down to:
Number(true) == Number([])
=> 1 == 0
const isTrue = true == []; // => false
Here, two booleans are present. The right side gets converted through the unary negation, and then negated. An empty array is truthy, converting and negating it yields false, so true == false.
const isFalse = true == ![]; // => false
This now evaluates to false + false, which is coerced to:
Number(false) + Number(false)
=> 0 + 0
console.log(isTrue + isFalse); // => prints 0