Filter's Predicate Function
What you'll learn: How to write functions that tell filter() which array elements to keep and which to discard.
The Core Idea
When you use filter(), you pass it a predicate function—a special type of callback that acts like a yes/no gatekeeper. This function examines each element and returns either true (keep this element) or false (discard it). The predicate function is what gives filter() its decision-making power.
What Makes a Good Predicate
A predicate function receives the same parameters as map() or forEach(): the current element, its index, and the full array. However, unlike map() (which transforms values), your predicate must return a boolean value.
Think of it like a bouncer at a club checking IDs. Each person (array element) approaches, the bouncer checks their credentials (runs your predicate logic), and decides: "You're in" (true) or "Not tonight" (false).
const ages = [15, 22, 18, 34, 12, 28];
// Predicate: is this person old enough?
const adults = ages.filter(function(age) {
return age >= 18; // Returns true or false
});
console.log(adults); // [22, 18, 34, 28]
The predicate age >= 18 evaluates to a boolean for each element. Only elements where the result is true make it into the new array.
Writing Clear Predicates
Your predicate can be as simple or complex as needed, but it should always return a boolean:
const products = [
{ name: 'Laptop', price: 999, inStock: true },
{ name: 'Mouse', price: 25, inStock: false },
{ name: 'Keyboard', price: 75, inStock: true }
];
const available = products.filter(function(product) {
return product.inStock && product.price < 500;
});
Key Takeaway: A predicate function is the decision-maker in filter()—it returns true to keep an element or false to exclude it, acting as a gatekeeper for your new array.