A predicate function is a function that returns a boolean value—that is, it returns true or false depending on whether a condition is satisfied.
In other words, a predicate tests something.
function isEven(number) {
return number % 2 === 0;
}- Input: a number
- Output:
trueif the number is even, otherwisefalse
Usage:
isEven(4); // true
isEven(5); // falsePredicate functions are very common in functions like .filter(), .find(), .some(), etc.
const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.filter((n) => n % 2 === 0);Here:
(n) => n % 2 === 0is the predicate function. For each element, it answers the question: “Does this element match the condition?”
const isAdult = (person) => person.age >= 18;- Returns
true→ person is an adult - Returns
false→ person is not
A predicate function = a yes/no question in code.
Examples:
isEven(n)isEmpty(str)hasPermission(user)isLoggedIn(session)
All of them evaluate a condition and return true or false.
Since you work with React Native and TypeScript, you'll see predicate functions a lot with things like:
items.find(item => item.id === targetId)Here the predicate is:
item => item.id === targetId