Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any value for what x === x returns false without NaN?

Tags:

javascript

Is there any value for what x === x returns false without NaN?

For example:

> x = 1
1
> x === x
true
> x = {}
{}
> x === x
true
> x = new Date()
Wed Nov 13 2013 15:44:22 GMT+0200 (EET)
> x === x
true
> x = NaN
NaN
> x === x
false

I see that the only value where x === x returns false is when isNaN(x) === true.

Is there another value of x for what x === x returns false? An official reference would be welcome!

like image 998
Ionică Bizău Avatar asked Nov 13 '13 13:11

Ionică Bizău


People also ask

Does === return false?

Note that === never causes type coercion, but checks for correct types first and yields false if they are not equal!

Why is NaN === NaN false?

Although either side of NaN===NaN contains the same value and their type is Number but they are not same. According to ECMA-262, either side of == or === contains NaN then it will result false value.

Does NaN return true or false?

If it returns true , x will make every arithmetic expression return NaN . This means that in JavaScript, isNaN(x) == true is equivalent to x - 0 returning NaN (though in JavaScript x - 0 == NaN always returns false, so you can't test for it).

Does NaN evaluate to false?

When NaN is one of the operands of any relational comparison ( > , < , >= , <= ), the result is always false . NaN compares unequal (via == , != , === , and !== ) to any other value — including to another NaN value.


1 Answers

The strict comparison between two equal non-NaN values will always be true (SLaks's answer correctly quotes the spec). However, it's possible for the expression x to change its value during the evaluation of the the equality. This can happen with property access when using accessor property descriptors (i.e., property getters):

foo = {};
Object.defineProperty(foo, "bar", {
    get: function() {
        return Math.random();
    }
})

foo.bar === foo.bar; // false

If you do this for the global object window (or global in Node), then you can see the x === x comparison fail for a global-scope variable:

Object.defineProperty(window, "bar", {
    get: function() {
        return Math.random();
    }
})

bar === bar; // false
like image 117
apsillers Avatar answered Oct 27 '22 00:10

apsillers