JavaScript indexOf vs includes performance

This is a short response I wrote to a question on /r/javascript. The user who asked it was curious whether there would be any performance difference between using indexOf or includes when trying to find a substring within a larger string. 
Let’s take a look at the ECMAScript specification to see what it says.  

In the case of indexOf vs includes, you’ll find them right next to each other here in the ECMAScript spec. The only difference is that includes checks if you’ve passed it a regular expression instead of a string, and throws an exception if you have. indexOf will accept a regular expression but always return -1, which isn’t too helpful.

So while includes will be a tiny, tiny amount slower because it has to check if you passed it a regex, in reality this will make no difference to how fast your code runs. You should use indexOf if you care about where the substring is in the original string. If you don’t care, just call includes because it makes the intent of your code more clear.

As another posted mentioned, indexOf won’t find the location of NaN values in an Array. For cases where you really need to find the first location of something that indexOf can’t find, and you don’t want to loop the array through yourself, then Array.prototype.findIndex is your friend. You can pass it a function that returns true when it sees the value you’re looking for. So [1, 2, 3, NaN, 4].findIndex(Number.isNaN) would return 3.

Leave a Reply

Your email address will not be published. Required fields are marked *