Search code examples
javascriptarraysnanpolyfills

Polyfill for Array.includes checking NaN


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?


Solution

  • 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));