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
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.
Yes? Cool! You might want to check out Web Weekly for more quick learnings. The last edition went out 18 days ago.