Published at
Updated at
Reading time
This post is part of my Today I learned series in which I share all my web development learnings.

I've been 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 holding different types like ['foo', 123, true, undefined, NaN]. To figure out if a value is included in this array you could use indexOf and check if the result is -1.

This works fine for all the values except NaN, because NaN === NaN evaluates to false. You can't test if NaN an array includes NaN using indexOf.

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

Array.prototype.includes fixes this behavior. 🎉

['foo', 123, true, undefined, NaN].includes(NaN) // true
Was this TIL post helpful?
Yes? Cool! You might want to check out Web Weekly for more quick learnings. The last edition went out 18 days ago.

Related Topics

Related Articles

About the author

Stefan standing in the park in front of a green background

Frontend nerd with over ten years of experience, "Today I Learned" blogger, conference speaker, Tiny helpers maintainer, and DevRel at Checkly.