Artboard 16Google Sheets iconSwift icon
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 15 days ago.

Related Topics

Related Articles