So first off this is not an issue I am facing. I was going through some Javascript blogs when I encountered the Array prototype methods of .indexOf and .includes. So if an array has NaN as a value, then probably indexOf is not going to be able to figure it out and I am left with using .includes. But my question here is, since the browser compatibility of includes actually excludes IE, what should be the alternative to detect the NaN check? I thought of constructing a polyfill by referring this

if (Array.prototype.includes) {
  Object.defineProperty(Array.prototype, "includes", {
    enumerable: false,
    value: function(obj) {
        var newArr = this.filter(function(el) {
          return el == obj;
        });
        return newArr.length > 0;
      }
  });
}

var arr = [NaN];
console.log(arr.includes(NaN));

But unfortunately, it is returning false as well. So what other options do I have? Or am I missing something out?

3 Answers

1
CertainPerformance On Best Solutions

You can include a polyfill for Number.isNaN as well, and then use it in your filter test - if both the obj and el pass Number.isNaN, then return true:

Number.isNaN = Number.isNaN || function(value) {     
    return value !== value;
}

// if (!Array.prototype.includes) {
  Object.defineProperty(Array.prototype, "includes", {
    enumerable: false,
    value: function(obj) {
        var newArr = this.filter(function(el) {
          return el == obj || Number.isNaN(el) && Number.isNaN(obj);
        });
        return newArr.length > 0;
      }
  });
// }

var arr = [NaN];
console.log(arr.includes(NaN));

1
Niet the Dark Absol On

Array#includes uses the Same-Value-Zero algorithm, which is not the same as ==.

Same-Value is provided by Object.is(), and you can manually check for -0 and +0 to get the "-Zero" part of the check.

The linked page includes a polyfill, although since the polyfill includes a step to make -0 and +0 different - which you don't want in a Same-Value-Zero algorithm - you can just leave it out and simplify accordingly:

function SameValueZero(x, y) {
    return x === y || (x !== x && y !== y);
}
0
Syed Mohamed Aladeen On

You can find the index of NaN using firstIndex. try like this.

var arr = [NaN];
let index = arr.findIndex(Number.isNaN)
console.log(index >= 0);