Can (a == 1 && a == 2 && a == 3) be evaluated as true?

8

This is an interview question:

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

Reference: Related question in SOen

    
asked by Marcos 24.01.2018 в 14:15
source

2 answers

13

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

A (Object) == B (Number)
  

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

Solution:

We can define a as an object with a toString (or valueOf ) method which changes its result each time it is invoked.

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 reply in SOen

    
answered by 24.01.2018 в 14:15
4

You could use defineProperty to define the method get of the object a , what it will do is define or increase an internal property and return its value:

Object.defineProperty(Window.prototype, 'a', {
  get: () => { 
    this.x = this.x || 1;
    return this.x++; 
  }
});

if (a == 1 && a == 2 && a == 3) {
  console.log("VERDAD")
}
    
answered by 24.01.2018 в 18:59