Aphiwad Chhoeun

Will (a == 1 && a == 2 && a == 3) ever be true?

Understanding comparison operator in JS

This is one of those Javacript WTF moments.

Question: Will (a == 1 && a == 2 && a == 3) ever evaluates true?

The answer is: YES!

Here’s why it works:

let a = {
  t: 1,
  valueOf() {
    return this.t++
  },
}

console.log(a == 1 && a == 2 && a == 3) // true

The loose comparison operator (==) converts the operands if they are not of the same type, then applies strict comparison. So in this case, the left operand is an object while the right operand is a number, so the valueOf() is called to convert it into the same type.

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators

See the Pen Will (a == 1 && a == 2 && a == 3) ever be true? by Aphiwad Chhoeun (@aphiwadchhoeun) on CodePen.