Your product could be here, in front of thousands of JavaScript developers. Sponsor this spot →
JavaScript Quiz

What do true == [] and true == ![] return?

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
Take the full quiz Next question →

More Type Coercion questions

  1. Why does ('b' + 'a' + + 'a' + 'a') return "banana"?
  2. Why does 1 + "2" + "2" return "122"?
  3. Why is false == '0' true in JavaScript?
  4. Why is 3 > 2 > 1 false in JavaScript?
  5. Why does [] + {} return "[object Object]"?

Related topics