Array Some Method
some() returns true if the callback returns a truthy value for at least one element, and false otherwise. Where includes() can only look for a value, some() takes a test, so it can check a property of an object, a range or a pattern.
const basket = [ { item: 'Socks', price: 6 }, { item: 'Coat', price: 85 }, { item: 'Scarf', price: 18 },];
console.log(basket.some((line) => line.price > 50));console.log(basket.some((line) => line.price > 100));This prints:
truefalseIt stops at the first match
Section titled “It stops at the first match”some() stops as soon as the callback returns a truthy value, because the answer is then known. The elements after the match are not visited at all, which saves work on a long array or an expensive test.
const temperatures = [14, 17, 26, 19, 28];
const anyHot = temperatures.some((temperature, index) => { console.log(`checking index ${index}: ${temperature}`); return temperature > 25;});
console.log(anyHot);This prints:
checking index 0: 14checking index 1: 17checking index 2: 26trueBecause of this, the callback should only test the element and not do other work that must happen for every element. For that, use forEach().
An empty array
Section titled “An empty array”On an empty array some() returns false without calling the callback, because no element can pass the test.
console.log([].some((value) => value > 0));This prints:
falseThe opposite question, whether every element passes, is answered by every().
Steve Griffith covers this topic in his video JavaScript Array some method.