JavaScript Predicate Functions Tutorial with Examples

In JavaScript, a predicate is a function that returns a boolean value, i.e., either true or false. Predicates are typically used to test conditions in higher-order functions like filter(), some(), and every().

They are commonly used to make decisions, filter data, or evaluate whether some criteria are met.

In this tutorial, we will cover:

  1. What is a Predicate Function?
  2. Using Predicates with Array.filter()
  3. Using Predicates with Array.some()
  4. Using Predicates with Array.every()
  5. Creating Custom Predicate Functions
  6. Combining Predicates
  7. Examples and Use Cases of Predicate Functions

Let's dive into each concept with examples.

1. What is a Predicate Function?

A predicate function is a function that accepts one or more arguments and returns either true or false. Predicate functions are often used in array operations or other contexts where filtering, validation, or checking conditions is necessary.

Example: Basic Predicate Function

// A simple predicate function to check if a number is even
function isEven(number) {
    return number % 2 === 0;
}

console.log(isEven(4));  // Output: true
console.log(isEven(7));  // Output: false

In this example:

  • The function isEven() checks whether a number is even.
  • It returns true if the number is even, and false if it is odd.

2. Using Predicates with Array.filter()

The filter() method is used to filter elements from an array based on a predicate function. It creates a new array with all elements that pass the test implemented by the predicate.

Example: Using a Predicate with filter()

// Predicate function to check if a number is greater than 10
function isGreaterThanTen(num) {
    return num > 10;
}

const numbers = [5, 12, 8, 130, 44];

// Using the predicate with filter to get numbers greater than 10
const filteredNumbers = numbers.filter(isGreaterThanTen);

console.log(filteredNumbers);  // Output: [12, 130, 44]

In this example:

  • The predicate function isGreaterThanTen() is used with filter().
  • Only numbers greater than 10 are included in the resulting array.

Example: Inline Predicate with filter()

You can also pass an inline predicate directly into the filter() function.

const numbers = [5, 12, 8, 130, 44];

// Using an inline predicate function
const evenNumbers = numbers.filter(num => num % 2 === 0);

console.log(evenNumbers);  // Output: [12, 8, 130, 44]

In this example, an inline arrow function is used to check whether each number is even.

3. Using Predicates with Array.some()

The some() method tests whether at least one element in the array passes the test implemented by the provided predicate function. It returns true if at least one element passes the test, and false otherwise.

Example: Using a Predicate with some()

// Predicate function to check if a number is greater than 100
function isGreaterThan100(num) {
    return num > 100;
}

const numbers = [5, 12, 8, 130, 44];

// Check if there is any number greater than 100
const hasLargeNumber = numbers.some(isGreaterThan100);

console.log(hasLargeNumber);  // Output: true

In this example:

  • The some() method checks if any number in the array is greater than 100.
  • Since 130 is greater than 100, it returns true.

4. Using Predicates with Array.every()

The every() method tests whether all elements in the array pass the test implemented by the provided predicate function. It returns true if all elements pass the test, and false otherwise.

Example: Using a Predicate with every()

// Predicate function to check if a number is less than 50
function isLessThan50(num) {
    return num < 50;
}

const numbers = [5, 12, 8, 44];

// Check if all numbers are less than 50
const allLessThan50 = numbers.every(isLessThan50);

console.log(allLessThan50);  // Output: true

const mixedNumbers = [5, 12, 60, 44];
const allLessThan50Mixed = mixedNumbers.every(isLessThan50);

console.log(allLessThan50Mixed);  // Output: false

In this example:

  • The every() method checks if all numbers are less than 50.
  • It returns true for the first array and false for the second array because 60 is not less than 50.

5. Creating Custom Predicate Functions

You can create custom predicate functions to suit specific conditions, such as checking object properties or performing complex logical tests.

Example: Predicate Function for Object Properties

// Predicate function to check if a person is an adult
function isAdult(person) {
    return person.age >= 18;
}

const people = [
    { name: "Alice", age: 17 },
    { name: "Bob", age: 25 },
    { name: "Charlie", age: 19 },
];

// Using the predicate with filter to get only adults
const adults = people.filter(isAdult);

console.log(adults);
// Output: [{ name: 'Bob', age: 25 }, { name: 'Charlie', age: 19 }]

In this example, we use the isAdult() predicate function to filter out people who are 18 or older.

6. Combining Predicates

You can combine predicate functions to create more complex conditions by using logical operators like && (AND) and || (OR).

Example: Combining Predicates with Logical AND

// Predicate function to check if a number is positive and even
function isPositiveAndEven(num) {
    return num > 0 && num % 2 === 0;
}

const numbers = [-1, 0, 2, 3, 4, -5];

// Filtering positive and even numbers
const positiveEvenNumbers = numbers.filter(isPositiveAndEven);

console.log(positiveEvenNumbers);  // Output: [2, 4]

Example: Combining Predicates with Logical OR

// Predicate function to check if a number is either less than 0 or greater than 100
function isLessThan0OrGreaterThan100(num) {
    return num < 0 || num > 100;
}

const numbers = [-5, 10, 50, 200, 0];

// Filtering numbers that are less than 0 or greater than 100
const extremeNumbers = numbers.filter(isLessThan0OrGreaterThan100);

console.log(extremeNumbers);  // Output: [-5, 200]

7. Examples and Use Cases of Predicate Functions

Example 1: Checking if Any Item in a List is Expensive

const items = [
    { name: "Laptop", price: 900 },
    { name: "Smartphone", price: 600 },
    { name: "Headphones", price: 50 },
];

// Predicate to check if an item costs more than 800
const isExpensive = item => item.price > 800;

// Checking if there are any expensive items
const hasExpensiveItem = items.some(isExpensive);

console.log(hasExpensiveItem);  // Output: true

Example 2: Filtering Valid Email Addresses

const emails = [
    "user@example.com",
    "invalid-email",
    "john.doe@example.com",
    "another-invalid-email",
];

// Predicate to check if an email is valid
function isValidEmail(email) {
    return email.includes("@") && email.includes(".");
}

// Filtering valid email addresses
const validEmails = emails.filter(isValidEmail);

console.log(validEmails);
// Output: ['user@example.com', 'john.doe@example.com']

In this example, the predicate function isValidEmail() checks if an email contains both “@” and “.” to determine if it is valid.

Example 3: Finding All Prime Numbers in a List

// Predicate function to check if a number is prime
function isPrime(num) {
    if (num <= 1) return false;
    for (let i = 2; i <= Math.sqrt(num); i++) {
        if (num % i === 0) return false;
    }
    return true;
}

const numbers = [2, 3, 4, 5, 6, 7, 8, 9, 10];

// Filtering prime numbers
const primeNumbers = numbers.filter(isPrime);

console.log(primeNumbers);  // Output: [2, 3, 5, 7]

Summary of Key Functions Used with Predicates

Function Description Example
filter() Filters elements that pass the predicate test. arr.filter(predicate)
some() Returns true if at least one element passes the test. arr.some(predicate)
every() Returns true if all elements pass the test. arr.every(predicate)
Custom Predicate Define a function to implement custom conditions. const isValid = item => item.isActive
Combining Predicates Combine multiple predicates with && or `

Conclusion

Predicate functions are essential for performing conditional checks and filtering data in JavaScript. In this tutorial, we covered:

  • What predicate functions are and how they return boolean values.
  • How to use predicates with array methods like filter(), some(), and every().
  • How to create custom predicate functions and combine them for complex conditions.

Related posts

JavaScript User-Defined Iterators Tutorial with Examples

JavaScript Template Literals Tutorial with Examples

JavaScript Reflect: A Comprehensive Tutorial