Actually, this question is an extension of Can (a== 1 && a ==2 && a==3) ever evaluate to true? .
As we may know, The secret of loose equality operator (==) will try to convert both values to a common type. As a result, some functions will be invoked.
ToPrimitive(A)
attempts to convert its object argument to a primitive value, by invoking varying sequences ofA.toString
andA.valueOf
methods on A.
So the following code will work as expected.
const a = {
i: 1,
toString: function () {
return a.i++;
}
}
if(a == 1 && a == 2 && a == 3) {
console.log('Hello World!');
}
However, The problem in the case of strict equality (===)
. Methods such as .valueOf
, .toString
, or Symbol.toPrimitive
won’t be called by JavaScript Engine.
How can I resolve it? Any help would be appreciated.
const a = {
i: 1,
toString: function () {
return a.i++;
}
}
if(a === 1 && a === 2 && a === 3) {
console.log('Never catch!');
}