Search code examples
javascriptarraysindexof

Why do indexOf() and findIndex() work differently with Number.isNaN?


I was trying to find NaN in array. And I've found this way to do it.

console.log([1, NaN, 3].findIndex(Number.isNaN)); //1

And then I've tried to do the same with indexOf. Why it's not working?

console.log([1, NaN, 3].indexOf(Number.isNaN)); //-1


Solution

  • If you look at the documentation of indexOf, you will see it does not take a function to compare. It does a strict equality so it is looking for Number.isNaN in the array.