Skip to content
Advertisement

In what situation would ‘a != a’ resolve to true in JavaScript?

Looking through the code of svelte.js I found this odd looking function:

function not_equal(a, b) {
    return a != a ? b == b : a !== b;
}

Can someone explain to me in what situation comparing a variable with it self for inequality would resolve to false?

I know that != and == are weaker comparison operators than !== and === because they don’t really care about the type but I still can’t figure out what makes the not_equal function different from a simple a !== b

Advertisement

Answer

There are a couple of ways:

1. If a is NaN: NaN is not equal to anything, including itself.

let a = NaN;
console.log(a != a); // true

I think this is the likely reason for that conditional operator in not_equal, since with that function not_equal(NaN, NaN) is false (e.g., it considers NaN equal to itself). It’s not clear to me why they went with the == rather than === in b == b, though.

2. (This doesn’t apply to your function, just the a != a question.) If a is a property with a getter function that returns a different value when called twice in succession (because it returns a random value, or a value that changes over time, or the getter mutates the value, etc.) being used within a with statement (very unlikely), or similar using a Proxy rather than a with.

const obj = {
    get a() {
        return Math.random();
    }
};
with (obj) {
    console.log(a != a); // PROBABLY true
}

(Note: There are very good reasons not to use with, and it can’t be used in strict mode.)

Other than that, I can’t think of a way a != a would be true.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement