0

In MDN polyfill function for Array.prototype.includes(), I found the following code.

function sameValueZero(x, y) {
    return x === y || (typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y));
}

In the above code typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y) this makes me confusing. If the typeof the variable is a number , isNaN will be always false right? so when this whole condition will return true? Can someone explain or did I understand it wrongly?

Vineesh
  • 3,762
  • 20
  • 37

3 Answers3

2

In JavaScript, the type of NaN is number. I guess this is because it is the result of mathematical operations.

See this question for more information.

Jonathan Lam
  • 16,831
  • 17
  • 68
  • 94
1

This code will return true if the 2 elements are NaN, but false if the both are not numbers.

As you can see, the 1st example returns true is both isNaN() regardless of their type - which makes a equal b. The 2nd checks if both are numbers before using isNaN():

const checkEq1 = (x, y) => isNaN(x) && isNaN(y)

console.log(checkEq1(NaN, NaN)); // true

console.log(checkEq1('a', 'b')); // true - error

const checkEq2 = (x, y) => typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y)

console.log(checkEq2(NaN, NaN)); // true

console.log(checkEq2('a', 'b')); // false
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
0

Nope, if typeof x === 'number', x can be NaN, and then isNaN(x) && typeof x === 'number' will both be true.

No idea why that function just doesn't use Number.isNaN(x) && Number.isNaN(y) though, since that will explicitly check if the value is NaN (as opposed to anything that can be NaN when converted to a number, as with isNaN).

doubleOrt
  • 2,407
  • 1
  • 14
  • 34