Hacker News new | ask | show | jobs
by mfonda 4443 days ago
I think there was a more general question here that was missed: can a == x && a == y ever be true for any arbitrary values of a, x, and y, where x != y.

From a logical point of view, no, this can never be true. I would suspect this can never be true in javascript, and could only be made true in a language where you can override == to always return true.

I think when most developers use the word "never", what they really mean is "never (within the current context)". This makes conversations a lot simpler. Imagine how difficult conversations would be if you always had to qualify never. "This can never be true (assuming a weird valueOf method hasn't been defined and assuming I didn't modify the javascript interpreter to always return true for == and assuming ...)".

3 comments

I think there are a few cases of non-transitive equalities in JavaScript, specifically around falsey values. Part of it also has to do with whether x is the right-side input or the left-side input, because that changes type coercion rules.

Aha, found one:

  ['0'] == 0
  > true
  [0] == 0
 > true
  [0] == ['0']
 > false
Transitivity of equality can also never be relied upon when dealing with Floating Point numbers. This is correct and unavoidable behavior, but still surprising to many developers.
That's not due to transitivity: ['0'] == ['0'] (and for that matter, ['0'] === ['0']) is also false. These operators compare objects for identity, not structural equality.
Something like this could work, to some degree:

        a = {}
        a.valueOf = function() {
           var caller = arguments.callee.caller.toString();
           //parse the caller function, and return 
           //different values based on what comparison is being made. 
        }
But I think this is even worse than the getter on the global object.
Here's a JavaScript example, based on what was in the article.

    var b = {c:0};
    b.valueOf = function() { this.c++; return this.c; }
    b == 1 && b == 2
    > true
That only works for consecutive integers, not any arbitrary values.