Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pure function given strictly equal arguments yielding non-strictly equal results

Tags:

javascript

Below is a pure function f for which f(a) !== f(b) despite a === b (notice the strict equalities) for some values of a and b:

var f = function (x) {
   return 1 / x;
}

+0 === -0 // true
f(+0) === f(-0) // false

The existence of such functions can lead to difficult-to-find bugs. Are there other examples I should be weary of?

like image 239
Randomblue Avatar asked Aug 28 '11 19:08

Randomblue


1 Answers

Yes, because NaN !== NaN.

var f = function (x) { return Infinity - x; }

Infinity === Infinity // true
f(Infinity) === f(Infinity) // false

f(Infinity) // NaN

Some other examples that yield NaN whose arguments can be strictly equal:

0/0
Infinity/Infinity
Infinity*0
Math.sqrt(-1)
Math.log(-1)
Math.asin(-2)
like image 115
Casey Chu Avatar answered Oct 21 '22 10:10

Casey Chu