Code Snippets
/

every, some, and Includes Patterns

every, some, and Includes Patterns

When you need to ask "do all of these match?" or "is there at least one match?", `Array.prototype.every` and `Array.prototype.some` give you boolean answers in one pass. This snippet covers those two plus the count-via-filter pattern for "how many match?" and a small predicate factory pattern that lets you compose these checks for form validation, feature flags, or permission rules.

JavaScript
Easy
4 snippets
arrays
map-filter-reduce
conditionals

704 views

10

// every() returns true only if the predicate returns truthy for every item.
const allEven = (arr) => arr.every((n) => n % 2 === 0);
console.log(allEven([2, 4, 6, 8])); // true
console.log(allEven([2, 4, 5, 8])); // false

// At least 10 across the board.
const allAtLeast10 = (arr) => arr.every((n) => n >= 10);
console.log(allAtLeast10([10, 20, 30])); // true
console.log(allAtLeast10([10, 5, 30]));  // false

// Form-validation flavor: every required field has a value.
const fields = [
    { name: 'email', value: '[email protected]' },
    { name: 'password', value: 'secret' }
];
console.log(fields.every((f) => f.value.length > 0)); // true

// Empty-array gotcha: every() returns true (vacuous truth).
console.log([].every((n) => n > 100)); // true

every is the right call when you want a single boolean answer to an all-of question. It short-circuits on the first failure, which makes it cheap on large arrays where mismatches happen early. The empty-array case is the only real gotcha: [].every(predicate) returns true because there is nothing that fails the test. Guard with an explicit arr.length > 0 if you want "at least one item AND all match".