Course contentsShow
← JavaScript
Lesson 467 of 2,72312. Higher-Order FunctionsFree lesson

Every with Predicate Functions

Use predicate functions with every() to validate that all array elements meet a condition.

Every with Predicate Functions

You'll learn how to use predicate functions with every() to elegantly validate that all array elements meet specific conditions.

What Are Predicate Functions?

A predicate function is simply a function that returns true or false. When you pass a predicate to every(), you're asking: "Does every element in this array satisfy this condition?"

Think of it like a quality inspector checking products on an assembly line—every single item must pass inspection, or the whole batch fails.

Using Predicates with Every

Instead of writing the test logic directly in every(), you can extract it into a named predicate function:

function isPositive(num) {
  return num > 0;
}

const scores = [5, 10, 3, 8];
const allPositive = scores.every(isPositive);
// true: all numbers are positive

This approach shines when you reuse the same validation logic:

function isAdult(person) {
  return person.age >= 18;
}

const group1 = [
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 30 }
];

const group2 = [
  { name: 'Charlie', age: 16 },
  { name: 'Diana', age: 22 }
];

group1.every(isAdult); // true
group2.every(isAdult); // false: Charlie is under 18

Why Use Named Predicates?

Named predicates make your code self-documenting. Compare:

// Less clear
users.every(u => u.age >= 18 && u.verified);

// Crystal clear
users.every(isEligibleUser);

You can also combine predicates for complex validations while keeping each function simple and testable.

Key Takeaway: Using named predicate functions with every() makes validation logic reusable, readable, and easier to test—turn complex conditions into meaningful function names.