Array.indexOf() vs Array.includes()

The Array.indexOf() and 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? 🤔

The indexOf() method

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…

var marvelCharacters = [ "The Punisher", "Daredevil", "Jessica Jones" ];

…And I wanted to know Jessica Jones’ position in the array, I could find it using the indexOf() method:

var jessicaJonesPosition = marvelCharacters.indexOf("Jessica Jones"); // 2

This returns 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 -1.

For example, if I tried to find Iron Fist, I would get -1, because he is not present in my marvelCharacters array:

var ironFistPosition = marvelCharacters.indexOf("Iron Fist"); // -1

So, to check if an element exists in an array, you just need to check if the indexOf() method returns a number greater than -1:

if (marvelCharacters.indexOf("The Punisher") > -1) {
  // This will run, since The Punisher is present in my array
}

The Array.indexOf() method is supported in all modern browsers and IE9+, which is solid nowadays.

The includes() method

The 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 includes() method:

if (marvelCharacters.includes("The Punisher")) {
  // This will run, since The Punisher is present in my array
}

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.

Summary

The indexOf() and 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 indexOf() method.


If you have questions, feedback, or any other suggestions, please do email me. I'd love to hear from you!