banner
raye~

Raye's Journey

且趁闲身未老,尽放我、些子疏狂。
medium
tg_channel
twitter
github
email
nintendo switch
playstation
steam_profiles

JavaScript weak type comparison? Implement a == 1 && a == 2 && a == 3

This is a short article about JavaScript features. I plan to write articles on these small knowledge points whenever I have time.

In JavaScript, define a variable a such that:

a == 1 && a == 2 && a == 3 === true

Solution 1: Rewrite the valueOf method#

  • Code Example:
let value = 0;
const a = {
    valueOf: function() {
        return ++value;
    }
};

console.assert(a==1 && a==2 && a==3, true);
  • Principle:

    • When a is used in comparison operations (e.g., a == 1), the JavaScript engine calls a.valueOf() to get its primitive value.
    • We rewrite the valueOf method to return an incremented value each time it is called.
  • Result:

    • First comparison: a.valueOf() returns 1, so a == 1.
    • Second comparison: a.valueOf() returns 2, so a == 2.
    • Third comparison: a.valueOf() returns 3, so a == 3.

Solution 2: Use a Proxy object#

  • Code Example:
let value = 0;
const a = new Proxy({}, {
    get: function(target, name) {
        return ++value;
    }
});

console.assert(a.anyProperty == 1 && a.anyProperty == 2 && a.anyProperty == 3, true);
  • Principle:

    • The Proxy object is used to create a proxy for an object, allowing us to intercept and customize fundamental operations, such as property access.
    • We intercept any property access on a and return an incremented value each time it is accessed.
  • Result:

    • Similar to the valueOf method, each property access returns an incremented value.
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.