includes really is the better indexOf

1 min read

This post is part of my Today I learned series in which I share all my learnings regarding web development.

That's a really quick one. I was sitting in Jeff Strauss' talk at KCDC on ES2017 and he mentioned a tiny detail about Array.prototype.includes I didn't think of before.

Let's say you have an array with several different types like ['foo', 123, true, undefined, NaN]. You could now figure out if these values are included in the array by using indexOf and checking if it returns -1, right? Well... :D

This works fine for all the values except NaN because NaN === NaN evaluates to false.

['foo', 123, true, undefined, NaN].indexOf(NaN) // -1

Array.prototype.includes fixes this behavior. ๐ŸŽ‰

['foo', 123, true, undefined, NaN].includes(NaN) // true