Array.includes() methods both let you check if an item exists in an array. So, what’s the difference? When should you use one method versus the other? 🤔
Strictly speaking, the
indexOf() method is used to get the first index at which a given element can be found in an array.
So, if I had an array of Marvel characters…
…And I wanted to know Jessica Jones’ position in the array, I could find it using the
2, since arrays are zero-indexed and she sits at the third position.
Here’s the trick: if the given element doesn’t exist in the array, the
indexOf() method returns
For example, if I tried to find Iron Fist, I would get
-1, because he is not present in my
So, to check if an element exists in an array, you just need to check if the
indexOf() method returns a number greater than
Array.indexOf() method is supported in all modern browsers and IE9+, which is solid nowadays.
includes() method is specifically designed to check if an array contains the given element. It returns
true if so, and
false if not.
So, I could refactor my last example using the
I personally find this easier to read, since it’s like reading plain English.
The biggest difference is that the
includes() method is not supported in IE whatsoever. If you need to support IE, you should include the polyfill for
includes() first. This will push the support back to IE9.
includes() methods both let you check if an item exists in an array. If you don’t mind including a polyfill, I’d go with the
includes() method since it’s much more readable. Otherwise, you can use the
If you have questions, feedback, or any other suggestions, please do email me. I'd love to hear from you!