javascript – Can (a == 1 && a == 2 && a == 3) evaluate to true?

Question:

This is an interview question:

Is it possible in Javascript that (a == 1 && a == 2 && a == 3) can evaluate to true ?


Reference: Related question in SOen

Answer:

If we analyze how the == operator works, we see that, for example, if variable A is an Object and it is compared against variable B of type Number , that is:

A (Object) == B (Number)

Before performing the ToPrimitive(A) comparison try to convert the object to a primitive type value by making several sequences of invocations to A.toString and A.valueOf on A

Solution:

We can define a as an object with a method toString (or valueOf ) which change the outcome every time you invoke it .

Example

let a = {
  i: 1, // Contador interno
  toString: () => {
    return a.i++;
  }
}

if (a == 1 && a == 2 && a == 3) {
  console.log('a == 1 && a == 2 && a == 3 es igual a true');
}

Reference: Original answer in SOen

Scroll to Top