includes really is the better indexOf (#tilPost)

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 […


This content originally appeared on Stefan Judis Web Development and was authored by Stefan Judis

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

Reply to Stefan


This content originally appeared on Stefan Judis Web Development and was authored by Stefan Judis


Print Share Comment Cite Upload Translate
APA
Stefan Judis | Sciencx (2022-12-01T20:32:50+00:00) » includes really is the better indexOf (#tilPost). Retrieved from https://www.scien.cx/2017/08/08/includes-really-is-the-better-indexof-tilpost/.
MLA
" » includes really is the better indexOf (#tilPost)." Stefan Judis | Sciencx - Tuesday August 8, 2017, https://www.scien.cx/2017/08/08/includes-really-is-the-better-indexof-tilpost/
HARVARD
Stefan Judis | Sciencx Tuesday August 8, 2017 » includes really is the better indexOf (#tilPost)., viewed 2022-12-01T20:32:50+00:00,<https://www.scien.cx/2017/08/08/includes-really-is-the-better-indexof-tilpost/>
VANCOUVER
Stefan Judis | Sciencx - » includes really is the better indexOf (#tilPost). [Internet]. [Accessed 2022-12-01T20:32:50+00:00]. Available from: https://www.scien.cx/2017/08/08/includes-really-is-the-better-indexof-tilpost/
CHICAGO
" » includes really is the better indexOf (#tilPost)." Stefan Judis | Sciencx - Accessed 2022-12-01T20:32:50+00:00. https://www.scien.cx/2017/08/08/includes-really-is-the-better-indexof-tilpost/
IEEE
" » includes really is the better indexOf (#tilPost)." Stefan Judis | Sciencx [Online]. Available: https://www.scien.cx/2017/08/08/includes-really-is-the-better-indexof-tilpost/. [Accessed: 2022-12-01T20:32:50+00:00]
rf:citation
» includes really is the better indexOf (#tilPost) | Stefan Judis | Sciencx | https://www.scien.cx/2017/08/08/includes-really-is-the-better-indexof-tilpost/ | 2022-12-01T20:32:50+00:00
https://github.com/addpipe/simple-recorderjs-demo