Mofey Here's the explanation...
1. The expressions are comparing an object `a` with numbers 1 and 2 in both instances. So... these comparisons involve different types.
2. The double equal sign (==) is a loose equality meaning it will first convert the operands into a common primitive type between the two, in this case, a Number.
3. Type coercion for the object will involve calling the `valueOf()` method first, which has been declared in the object definition.
The first reference to (a==1 && ... ) invokes a call to `a.valueOf()` which increments `a.num` from 0 to 1. The 2nd reference ( ... && a==2) invokes the same method, incrementing `a.num` and returning 2.
Therefore, the equality check above essentially becomes:
(1==1 && 2==2)
Both evaluate to true.
Here's are some articles I found to help you grasp this more clearly:
When we assign an object to a variable, the reference of the object is what the variable holds and not the object itself.
So, when assigning an object to a constant variable, the reference of the object becomes constant to that variable and not to the object itself. Therefore, the object is mutable.
Santanu Sikder `const` is applied to the object, not the number itself. This doesn't make the object immutable. It only makes it such that the reference to the object for the symbol `a` cannot be changed.
That said, I find it whacked that the equality check is being made between an object and two numbers. 😂🤣
I mean... who does that? 🤦♂️🤷♂️
According to me, each time the object a is appearing in the equality check, its member function valueOf() is also run. And everytime it is run, it does this.num += 1 and returns that value.
So, initially num = 0; then on the first call to a (in the equality check), this happens:
num = 0;
num += 1; // = 1, by the valueOf() function
return num; // Returns 1
and, a == 1 returns true.
Then, on the second call to a (in the equality check), this happens:
num = 1; // After the previous increment by valueOf()
num += 1; // = 2, by the valueOf() function
return num; // Returns 2
and this time, a == 2 returns true.
Since both of them return true, && operator returns true and hence, the check returns true.
But one question- What is the use of the const keyword here, if num isn't constant?