0

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 of A.toString and A.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!');
}
Nguyễn Văn Phong
  • 13,506
  • 17
  • 39
  • 56
  • 2
    Please read all the answer of the question you linked. Many will work with `===` as well. – Bergi Apr 17 '21 at 02:18
  • @Bergi I did. But none of them pointed out it works with `strict equality (===)`. Besides, I did google, searched on SO no existing topics like this. So IMO, it's worth having a specific topic like this :) – Nguyễn Văn Phong Apr 17 '21 at 02:27

1 Answers1

7

Some of the methods on the other page work with strict equality, just avoid the ones that utilize toString or valueOf.

let num = 1;
Object.defineProperty(window, 'a', { get() { return num++ } });
// or use `with` and an object with a getter instead of putting it on the window

if(a === 1 && a === 2 && a === 3) {
  console.log('Never catch!');
}

This works because a is not a normal variable - it's a getter on the window, so when the identifier a is referenced, the getter runs and can return any value. Here, it'll return an incremented integer.

Other methods in the linked question will work with strict equality, if you wish to permit them:

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320