

includes() to see if an array includes an item unless your array has more than 100,000 items. How big does your data have to be for you to want to sacrifice code readability for performance? Later, I test that hypothesis.Ĭheck out this JavaScript code example demonstrating four variations of finding out whether an array has a given value: (This is similar to the difference between. some() does that without creating an extra array. So if you need to test to see if any item in the array matches an arbitrary conditional. filter(), but does not return the array of matching items - just true or false. some() method allows an arbitrary conditional, like. “The some() method tests whether at least one element in the array passes the test implemented by the provided function. There is also the related () method, which is basically halfway between.

length > 0, you’ll know if the array contains at least one of the values matched. If you check whether the array returned by. “The filter() method creates a new array with all elements that pass the test implemented by the provided function.” - MDN Docs If later on you need to work with the items that you matched, or change the inclusion criteria to an arbitrary condition, you’ll need to use. filter() method lets you test the entire array with an arbitrary criteria, and it returns a new array of all the matching items. If you need to return the first matching item, you’d use () instead of. “The includes() method determines whether an array includes a certain value among its entries, returning true or false as appropriate.” - MDN Docs The most obvious alternative is (), but using () might save you future refactoring. If you need to know if a JavaScript array contains an item, you have a couple of options other than just writing a for loop.
