There are good reasons to use the String.prototype.indexOf() and Array.prototype.filter() methods. For example, you're trying to find where a certain substring begins in a string; or you want to only display items in a collection of people where the last name is "Smith." That's where they're fine. But where they are not fine are in instances like the following:
While the above code will work just fine, it's not really doing what you want. The better string method to use here is .includes()
That code snippet is much more clear in its intent, and uses fewer characters to write! Now, this is pretty much the only wrong use of .indexOf(). String.prototype .indexOf() is a String method, but it is also an Array method, and the Array method can be used just as incorrectly! At least Array has an .includes() method that works the same way! Consider the following:
Now let's focus on a few more code snippets that use Array.prototype.filter() incorrectly and what can be used in their place. We will be using the following collection of Pets that I made up on the spot for the next few functions.
Now, I'm not saying that you can't ever use Array.prototype.filter() ever. As I said already, it has its uses, like when you want to get all neutered pets.
What you shouldn't be using this method for, is for just fetching one pet. Or seeing if any of the pets in your collection have been spayed. Or to see if all of them are at least five years old. Each incorrect snippet has a corresponding correct snippet, and you can clearly tell what the function is supposed to do by the method names used.
.find() is like .filter() except it only returns the first element in the array that matches the iterator function.
.some() is like .filter() except it returns a Boolean value; true if at least one element matches the iterator function.
.every() is like .some() except it only returns true if all elements match the iterator function.