includes really is the better indexOf
Written by Stefan Judis
- Published at
- Updated at
- Reading time
- 1min
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 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 fixes this behavior. 🎉
['foo', 123, true, undefined, NaN].includes(NaN) // true
If you enjoyed this article...
Join 6.1k readers and learn something new every week with Web Weekly.
Reply to this post and share your thoughts via good old email.
