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 Updates
APA

Stefan Judis | Sciencx (2017-08-08T05:00:00+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 ,<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 ]. 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 . 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: ]
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/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.