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
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
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 toA.toStringandA.valueOfinA.
We can define a as an object with a toString (or valueOf ) method which changes its result each time it is invoked.
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
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")
}